Пример #1
0
 protected void triggerReloadWithNewTransaction(String id) {
   if (TransactionHelper.isTransactionMarkedRollback()) {
     throw new AssertionError("The calling transaction is marked rollback");
   } else if (TransactionHelper.isTransactionActive()) { // should flush
     // the calling
     // transaction
     TransactionHelper.commitOrRollbackTransaction();
     TransactionHelper.startTransaction();
   }
   try {
     try {
       triggerReload(id);
     } catch (RuntimeException cause) {
       TransactionHelper.setTransactionRollbackOnly();
       throw cause;
     }
   } finally {
     if (TransactionHelper.isTransactionActiveOrMarkedRollback()) {
       boolean wasRollbacked = TransactionHelper.isTransactionMarkedRollback();
       TransactionHelper.commitOrRollbackTransaction();
       TransactionHelper.startTransaction();
       if (wasRollbacked) {
         TransactionHelper.setTransactionRollbackOnly();
       }
     }
   }
 }
Пример #2
0
 @Override
 public void run() {
   log.info("start of thread " + Thread.currentThread().getName());
   try {
     TransactionHelper.startTransaction();
     CoreSession s = null;
     try {
       s = openSessionAs(SecurityConstants.ADMINISTRATOR);
       Thread.sleep(sleepMillis);
     } finally {
       try {
         if (s != null) {
           closeSession(s);
         }
       } finally {
         TransactionHelper.commitOrRollbackTransaction();
       }
     }
   } catch (Exception e) {
     if (threadException == null) {
       threadException = e;
     }
   }
   log.info("end of thread " + Thread.currentThread().getName());
 }
Пример #3
0
  @GET
  public Blob convert(
      @QueryParam("converter") String converter,
      @QueryParam("type") String type,
      @QueryParam("format") String format,
      @Context UriInfo uriInfo) {
    BlobHolder bh = getBlobHolderToConvert();

    boolean txWasActive = false;
    try {
      if (TransactionHelper.isTransactionActive()) {
        txWasActive = true;
        TransactionHelper.commitOrRollbackTransaction();
      }

      if (StringUtils.isNotBlank(converter)) {
        return convertWithConverter(bh, converter, uriInfo);
      } else if (StringUtils.isNotBlank(type)) {
        return convertWithMimeType(bh, type, uriInfo);
      } else if (StringUtils.isNotBlank(format)) {
        return convertWithFormat(bh, format, uriInfo);
      } else {
        throw new IllegalParameterException("No converter, type or format parameter specified");
      }
    } finally {
      if (txWasActive && !TransactionHelper.isTransactionActiveOrMarkedRollback()) {
        TransactionHelper.startTransaction();
      }
    }
  }
Пример #4
0
  protected void awaitCollectionWorks() throws InterruptedException {
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    workManager.awaitCompletion(
        CollectionConstants.COLLECTION_QUEUE_ID, WORK_TIME_OUT_MS, TimeUnit.MILLISECONDS);

    assertEquals(0, workManager.getQueueSize(CollectionConstants.COLLECTION_QUEUE_ID, null));
  }
 protected void setPermission(
     DocumentModel doc, String userName, String permission, boolean isGranted) {
   ACP acp = session.getACP(doc.getRef());
   ACL localACL = acp.getOrCreateACL(ACL.LOCAL_ACL);
   localACL.add(new ACE(userName, permission, isGranted));
   session.setACP(doc.getRef(), acp, true);
   TransactionHelper.commitOrRollbackTransaction();
   TransactionHelper.startTransaction();
 }
Пример #6
0
 @Test
 public void doesntLeakWithoutTx() {
   TransactionHelper.commitOrRollbackTransaction();
   try {
     checkSessionLeak();
   } finally {
     TransactionHelper.startTransaction();
   }
 }
Пример #7
0
 public void startTransaction() {
   if (syncMode) {
     ElasticSearchInlineListener.useSyncIndexing.set(true);
   }
   if (!TransactionHelper.isTransactionActive()) {
     TransactionHelper.startTransaction();
   }
   Assert.assertEquals(0, esa.getPendingWorkerCount());
   commandProcessed = esa.getTotalCommandProcessed();
 }
 protected void resetPermissions(DocumentRef docRef, String userName) {
   ACP acp = session.getACP(docRef);
   ACL localACL = acp.getOrCreateACL(ACL.LOCAL_ACL);
   Iterator<ACE> localACLIt = localACL.iterator();
   while (localACLIt.hasNext()) {
     ACE ace = localACLIt.next();
     if (userName.equals(ace.getUsername())) {
       localACLIt.remove();
     }
   }
   session.setACP(docRef, acp, true);
   TransactionHelper.commitOrRollbackTransaction();
   TransactionHelper.startTransaction();
 }
  protected void commit(boolean force) {
    uploadedFiles++;
    if (uploadedFiles % 10 == 0) {
      GenericMultiThreadedImporter.addCreatedDoc(taskId, uploadedFiles);
    }

    if (uploadedFiles % batchSize == 0 || force) {
      Stopwatch stopwatch =
          SimonManager.getStopwatch("org.nuxeo.ecm.platform.importer.session_save");
      Split split = stopwatch.start();
      fslog("Committing Core Session after " + uploadedFiles + " files", true);
      session.save();
      TransactionHelper.commitOrRollbackTransaction();
      TransactionHelper.startTransaction(transactionTimeout);
      split.stop();
    }
  }
Пример #10
0
  @Test
  public void shouldFilterLogEntriesOnEventCategories() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    List<LogEntry> logEntries = new ArrayList<>();
    LogEntry logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("secondEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("Two");
    logEntry.setEventId("firstEvent");
    logEntries.add(logEntry);
    auditLogger.addLogEntries(logEntries);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("category", "One");
    queryParams.add("category", "Two");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(3, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.add("category", "Two");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(1, nodes.size());
  }
  protected void flushAndSync() throws Exception {

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    Assert.assertTrue(Framework.getLocalService(AuditLogger.class).await(10, TimeUnit.SECONDS));

    esa.getClient()
        .admin()
        .indices()
        .prepareFlush(esa.getIndexNameForType(ElasticSearchConstants.ENTRY_TYPE))
        .execute()
        .actionGet();
    esa.getClient()
        .admin()
        .indices()
        .prepareRefresh(esa.getIndexNameForType(ElasticSearchConstants.ENTRY_TYPE))
        .execute()
        .actionGet();
  }
 public synchronized void run() {
   TransactionHelper.startTransaction(transactionTimeout);
   synchronized (this) {
     if (isRunning) {
       throw new IllegalStateException("Task already running");
     }
     isRunning = true;
     // versions have no path, target document can be null
     if (rootSource == null) {
       isRunning = false;
       throw new IllegalArgumentException("source node must be specified");
     }
   }
   try {
     session = CoreInstance.openCoreSessionSystem(repositoryName);
     log.info("Starting new import task");
     if (rootDoc != null) {
       // reopen the root to be sure the session is valid
       rootDoc = session.getDocument(rootDoc.getRef());
     }
     recursiveCreateDocumentFromNode(rootDoc, rootSource);
     session.save();
     GenericMultiThreadedImporter.addCreatedDoc(taskId, uploadedFiles);
     TransactionHelper.commitOrRollbackTransaction();
   } catch (Exception e) { // deals with interrupt below
     log.error("Error during import", e);
     ExceptionUtils.checkInterrupt(e);
     notifyImportError();
   } finally {
     log.info("End of task");
     if (session != null) {
       session.close();
       session = null;
     }
     synchronized (this) {
       isRunning = false;
     }
   }
 }
 @Override
 public void handleEvent(Event event) {
   if (!Framework.isDevModeSet()) {
     log.info("Do not flush the directory caches: dev mode is not set");
     return;
   }
   if (!ReloadEventNames.RELOAD_EVENT_ID.equals(event.getId())) {
     return;
   }
   try {
     RepositoryManager rm = Framework.getService(RepositoryManager.class);
     // Transaction management
     final boolean txStarted =
         !TransactionHelper.isTransactionActive() && TransactionHelper.startTransaction();
     boolean txSucceed = false;
     try {
       new UnrestrictedSessionRunner(rm.getDefaultRepositoryName()) {
         @Override
         public void run() {
           DocumentRoutingService service =
               Framework.getLocalService(DocumentRoutingService.class);
           service.importAllRouteModels(session);
         }
       }.runUnrestricted();
       txSucceed = true;
     } finally {
       if (txStarted) {
         if (!txSucceed) {
           TransactionHelper.setTransactionRollbackOnly();
           log.warn("Rollbacking import of route models");
         }
         TransactionHelper.commitOrRollbackTransaction();
       }
     }
   } catch (NuxeoException e) {
     log.error("Error while reloading the route models", e);
   }
 }
Пример #14
0
 @Test
 public void doesntReleaseBeforeCommit() {
   TransactionHelper.commitOrRollbackTransaction();
   assertEquals(0, activeConnectionCount());
   assertEquals(0, threadAllocatedConnectionsCount());
   closeSession();
   TransactionHelper.startTransaction();
   try {
     try (CoreSession first = openSessionAs("jdoe")) {
       assertEquals(1, threadAllocatedConnectionsCount());
       assertEquals(1, activeConnectionCount());
       try (CoreSession second = openSessionAs("jdoe")) {
         assertEquals(2, threadAllocatedConnectionsCount());
         assertEquals(1, activeConnectionCount());
         TransactionHelper.commitOrRollbackTransaction();
         assertEquals(0, threadAllocatedConnectionsCount());
         assertEquals(0, activeConnectionCount());
       }
     }
     assertEquals(0, threadAllocatedConnectionsCount());
   } finally {
     TransactionHelper.commitOrRollbackTransaction();
   }
 }
Пример #15
0
 protected void nextTransaction() {
   if (TransactionHelper.isTransactionActiveOrMarkedRollback()) {
     TransactionHelper.commitOrRollbackTransaction();
     TransactionHelper.startTransaction();
   }
 }
  @Test
  public void testClientSideUser1() throws Exception {

    // ---------------------------------------------
    // Check active factories
    // ---------------------------------------------
    TopLevelFolderItemFactory topLevelFolderItemFactory =
        fileSystemItemAdapterService.getTopLevelFolderItemFactory();
    assertEquals(
        "org.nuxeo.drive.hierarchy.permission.factory.PermissionTopLevelFactory",
        topLevelFolderItemFactory.getName());

    Set<String> activeFactories = fileSystemItemAdapterService.getActiveFileSystemItemFactories();
    assertEquals(5, activeFactories.size());
    assertTrue(activeFactories.contains("collectionSyncRootFolderItemFactory"));
    assertTrue(activeFactories.contains("defaultFileSystemItemFactory"));
    assertTrue(activeFactories.contains("userSyncRootParentFactory"));
    assertTrue(activeFactories.contains("permissionSyncRootFactory"));
    assertTrue(activeFactories.contains("sharedSyncRootParentFactory"));

    // ---------------------------------------------
    // Check top level folder: "Nuxeo Drive"
    // ---------------------------------------------
    Blob topLevelFolderJSON =
        (Blob) clientSession1.newRequest(NuxeoDriveGetTopLevelFolder.ID).execute();
    assertNotNull(topLevelFolderJSON);

    PermissionTopLevelFolderItem topLevelFolder =
        mapper.readValue(topLevelFolderJSON.getStream(), PermissionTopLevelFolderItem.class);

    assertNotNull(topLevelFolder);
    assertEquals(TOP_LEVEL_ID, topLevelFolder.getId());
    assertNull(topLevelFolder.getParentId());
    assertEquals("/" + TOP_LEVEL_ID, topLevelFolder.getPath());
    assertEquals("Nuxeo Drive", topLevelFolder.getName());
    assertTrue(topLevelFolder.isFolder());
    assertEquals("system", topLevelFolder.getCreator());
    assertEquals("system", topLevelFolder.getLastContributor());
    assertFalse(topLevelFolder.getCanRename());
    assertFalse(topLevelFolder.getCanDelete());
    assertFalse(topLevelFolder.getCanCreateChild());

    /**
     *
     *
     * <pre>
     * ===================================================
     * User workspace registered as a synchronization root
     * ===================================================
     * => Expected client side for user1:
     *
     * Nuxeo Drive
     *   |-- My Docs
     *   |     |-- user1File2
     *   |     |-- user1Folder1
     *   |     |     |-- user1File1
     *   |     |     |-- user1Folder2
     *   |     |-- user1Folder3
     *   |     |      |-- user1File3
     *   |     |-- user1Folder4
     *   |
     *   |-- Other Docs
     *   |     |-- user2Folder1
     *   |     |     |-- user2File1
     *   |     |     |-- user2Folder2
     *   |     |-- user2Folder3
     *   |     |     |-- user2File3
     *
     * </pre>
     */
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    nuxeoDriveManager.registerSynchronizationRoot(
        session1.getPrincipal(), userWorkspace1, session1);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    // ---------------------------------------------
    // Check top level folder children
    // ---------------------------------------------
    Blob topLevelChildrenJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", topLevelFolder.getId())
                .execute();

    ArrayNode topLevelChildren =
        mapper.readValue(topLevelChildrenJSON.getStream(), ArrayNode.class);
    assertNotNull(topLevelChildren);
    assertEquals(2, topLevelChildren.size());

    // Check "My Docs"
    UserSyncRootParentFolderItem userSyncRootParent =
        mapper.readValue(topLevelChildren.get(0), UserSyncRootParentFolderItem.class);
    assertEquals(userWorkspace1ItemId, userSyncRootParent.getId());
    assertEquals(TOP_LEVEL_ID, userSyncRootParent.getParentId());
    assertEquals(userWorkspace1ItemPath, userSyncRootParent.getPath());
    assertEquals("My Docs", userSyncRootParent.getName());
    assertTrue(userSyncRootParent.isFolder());
    assertEquals("user1", userSyncRootParent.getCreator());
    assertEquals("user1", userSyncRootParent.getLastContributor());
    assertFalse(userSyncRootParent.getCanRename());
    assertFalse(userSyncRootParent.getCanDelete());
    // Can create a child since "My Docs" is the user workspace
    assertTrue(userSyncRootParent.getCanCreateChild());

    // Check "Other Docs"
    SharedSyncRootParentFolderItem sharedSyncRootParent =
        mapper.readValue(topLevelChildren.get(1), SharedSyncRootParentFolderItem.class);
    assertEquals(SHARED_SYNC_ROOT_PARENT_ID, sharedSyncRootParent.getId());
    assertEquals(TOP_LEVEL_ID, sharedSyncRootParent.getParentId());
    assertEquals(
        "/" + TOP_LEVEL_ID + "/" + SHARED_SYNC_ROOT_PARENT_ID, sharedSyncRootParent.getPath());
    assertEquals("Other Docs", sharedSyncRootParent.getName());
    assertTrue(sharedSyncRootParent.isFolder());
    assertEquals("system", sharedSyncRootParent.getCreator());
    assertEquals("system", sharedSyncRootParent.getLastContributor());
    assertFalse(sharedSyncRootParent.getCanRename());
    assertFalse(sharedSyncRootParent.getCanDelete());
    assertFalse(sharedSyncRootParent.getCanCreateChild());

    // --------------------------------------------
    // Check user synchronization roots
    // --------------------------------------------
    Blob userSyncRootsJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", userSyncRootParent.getId())
                .execute();

    ArrayNode userSyncRoots = mapper.readValue(userSyncRootsJSON.getStream(), ArrayNode.class);
    assertNotNull(userSyncRoots);
    assertEquals(4, userSyncRoots.size());

    DocumentBackedFolderItem folderItem;
    DocumentBackedFileItem childFileItem;
    DocumentBackedFileItem fileItem;
    DocumentBackedFolderItem childFolderItem;

    JsonNode[] rootNodes = sortNodeByName(userSyncRoots);

    // user1File2
    fileItem = mapper.readValue(rootNodes[0], DocumentBackedFileItem.class);
    checkFileItem(
        fileItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        user1File2,
        userWorkspace1ItemId,
        userWorkspace1ItemPath,
        "user1File2.txt",
        "user1",
        "user1");

    // user1Folder1
    folderItem = mapper.readValue(rootNodes[1], DocumentBackedFolderItem.class);
    checkFolderItem(
        folderItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        user1Folder1,
        userWorkspace1ItemId,
        userWorkspace1ItemPath,
        "user1Folder1",
        "user1",
        "user1");
    Blob folderItemChildrenJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", folderItem.getId())
                .execute();
    ArrayNode folderItemChildren =
        mapper.readValue(folderItemChildrenJSON.getStream(), ArrayNode.class);
    assertNotNull(folderItemChildren);
    assertEquals(2, folderItemChildren.size());
    {
      JsonNode[] nodes = sortNodeByName(folderItemChildren);

      // user1File1
      childFileItem = mapper.readValue(nodes[0], DocumentBackedFileItem.class);
      checkFileItem(
          childFileItem,
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
          user1File1,
          folderItem.getId(),
          folderItem.getPath(),
          "user1File1.txt",
          "user1",
          "user1");

      // user1Folder2
      childFolderItem = mapper.readValue(nodes[1], DocumentBackedFolderItem.class);
      checkFolderItem(
          childFolderItem,
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
          user1Folder2,
          folderItem.getId(),
          folderItem.getPath(),
          "user1Folder2",
          "user1",
          "user1");
    }

    // user1Folder3
    folderItem = mapper.readValue(rootNodes[2], DocumentBackedFolderItem.class);
    checkFolderItem(
        folderItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        user1Folder3,
        userWorkspace1ItemId,
        userWorkspace1ItemPath,
        "user1Folder3",
        "user1",
        "user1");
    {
      folderItemChildrenJSON =
          (Blob)
              clientSession1
                  .newRequest(NuxeoDriveGetChildren.ID)
                  .set("id", folderItem.getId())
                  .execute();
      folderItemChildren = mapper.readValue(folderItemChildrenJSON.getStream(), ArrayNode.class);
      assertNotNull(folderItemChildren);
      assertEquals(1, folderItemChildren.size());
      // user1File3
      childFileItem = mapper.readValue(folderItemChildren.get(0), DocumentBackedFileItem.class);
      checkFileItem(
          childFileItem,
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
          user1File3,
          folderItem.getId(),
          folderItem.getPath(),
          "user1File3.txt",
          "user1",
          "user1");
    }

    // user1Folder4
    folderItem = mapper.readValue(rootNodes[3], DocumentBackedFolderItem.class);
    checkFolderItem(
        folderItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        user1Folder4,
        userWorkspace1ItemId,
        userWorkspace1ItemPath,
        "user1Folder4",
        "user1",
        "user1");

    // ---------------------------------------------
    // Check shared synchronization roots
    // ---------------------------------------------
    Blob sharedSyncRootsJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", sharedSyncRootParent.getId())
                .execute();

    List<DefaultSyncRootFolderItem> sharedSyncRoots =
        mapper.readValue(
            sharedSyncRootsJSON.getStream(),
            new TypeReference<List<DefaultSyncRootFolderItem>>() {});
    Collections.sort(sharedSyncRoots);

    assertNotNull(sharedSyncRoots);
    assertEquals(2, sharedSyncRoots.size());

    // user2Folder1
    DefaultSyncRootFolderItem sharedSyncRoot = sharedSyncRoots.get(0);
    checkFolderItem(
        sharedSyncRoot,
        SYNC_ROOT_ID_PREFIX,
        session1.getDocument(user2Folder1.getRef()),
        sharedSyncRootParent.getId(),
        sharedSyncRootParent.getPath(),
        "user2Folder1",
        "user2",
        "user1");
    Blob sharedSyncRootChildrenJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", sharedSyncRoot.getId())
                .execute();
    ArrayNode sharedSyncRootChildren =
        mapper.readValue(sharedSyncRootChildrenJSON.getStream(), ArrayNode.class);
    assertNotNull(sharedSyncRootChildren);
    assertEquals(2, sharedSyncRootChildren.size());
    DocumentBackedFolderItem sharedSyncRootChildFolderItem;
    DocumentBackedFileItem sharedSyncRootChildFileItem;
    {
      JsonNode[] nodes = sortNodeByName(sharedSyncRootChildren);
      // user2File1
      sharedSyncRootChildFileItem = mapper.readValue(nodes[0], DocumentBackedFileItem.class);
      checkFileItem(
          sharedSyncRootChildFileItem,
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
          session1.getDocument(user2File1.getRef()),
          sharedSyncRoot.getId(),
          sharedSyncRoot.getPath(),
          "user2File1.txt",
          "user2",
          "user2");
      // user2Folder2
      sharedSyncRootChildFolderItem = mapper.readValue(nodes[1], DocumentBackedFolderItem.class);
      checkFolderItem(
          sharedSyncRootChildFolderItem,
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
          session1.getDocument(user2Folder2.getRef()),
          sharedSyncRoot.getId(),
          sharedSyncRoot.getPath(),
          "user2Folder2",
          "user2",
          "user2");
    }
    // user2Folder3
    sharedSyncRoot = sharedSyncRoots.get(1);
    checkFolderItem(
        sharedSyncRoot,
        SYNC_ROOT_ID_PREFIX,
        session1.getDocument(user2Folder3.getRef()),
        sharedSyncRootParent.getId(),
        sharedSyncRootParent.getPath(),
        "user2Folder3",
        "user2",
        "user1");
    sharedSyncRootChildrenJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", sharedSyncRoot.getId())
                .execute();
    sharedSyncRootChildren =
        mapper.readValue(sharedSyncRootChildrenJSON.getStream(), ArrayNode.class);
    assertNotNull(sharedSyncRootChildren);
    assertEquals(1, sharedSyncRootChildren.size());
    // user2File3
    sharedSyncRootChildFileItem =
        mapper.readValue(sharedSyncRootChildren.get(0), DocumentBackedFileItem.class);
    checkFileItem(
        sharedSyncRootChildFileItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        session1.getDocument(user2File3.getRef()),
        sharedSyncRoot.getId(),
        sharedSyncRoot.getPath(),
        "user2File3.txt",
        "user2",
        "user2");

    /**
     *
     *
     * <pre>
     * =======================================================
     * User workspace NOT registered as a synchronization root
     * =======================================================
     * => Expected client side for user1:
     *
     * Nuxeo Drive
     *   |-- My Docs
     *   |
     *   |-- Other Docs (unchanged)
     *   |     |-- user2Folder1
     *   |     |     |-- user2File1
     *   |     |     |-- user2Folder2
     *   |     |-- user2Folder3
     *   |     |     |-- user2File3
     *
     * </pre>
     */
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    nuxeoDriveManager.unregisterSynchronizationRoot(
        session1.getPrincipal(), userWorkspace1, session1);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    // ---------------------------------------------
    // Check "My Docs"
    // ---------------------------------------------
    Blob userSyncRootParentJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetFileSystemItem.ID)
                .set("id", userWorkspace1ItemId)
                .execute();
    assertNotNull(userSyncRootParentJSON);

    userSyncRootParent =
        mapper.readValue(userSyncRootParentJSON.getStream(), UserSyncRootParentFolderItem.class);
    assertEquals(userWorkspace1ItemId, userSyncRootParent.getId());
    assertEquals(TOP_LEVEL_ID, userSyncRootParent.getParentId());
    assertEquals(userWorkspace1ItemPath, userSyncRootParent.getPath());
    assertEquals("My Docs", userSyncRootParent.getName());
    assertTrue(userSyncRootParent.isFolder());
    assertEquals("user1", userSyncRootParent.getCreator());
    assertEquals("user1", userSyncRootParent.getLastContributor());
    assertFalse(userSyncRootParent.getCanRename());
    assertFalse(userSyncRootParent.getCanDelete());
    // Cannot create a child since "My Docs" is only the parent of the
    // synchronization roots, not the user workspace
    assertFalse(userSyncRootParent.getCanCreateChild());

    // --------------------------------------------
    // Check user synchronization roots
    // --------------------------------------------
    userSyncRootsJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", userSyncRootParent.getId())
                .execute();

    userSyncRoots = mapper.readValue(userSyncRootsJSON.getStream(), ArrayNode.class);
    assertNotNull(userSyncRoots);
    assertEquals(0, userSyncRoots.size());

    /**
     *
     *
     * <pre>
     * =======================================================
     * User workspace NOT registered as a synchronization root
     * but specific folders yes: user1Folder3, user1Folder4
     * =======================================================
     * => Expected client side for user1:
     *
     * Nuxeo Drive
     *   |-- My Docs
     *   |     |-- user1Folder3
     *   |     |      |-- user1File3
     *   |     |-- user1Folder4
     *   |
     *   |-- Other Docs (unchanged)
     *   |     |-- user2Folder1
     *   |     |     |-- user2File1
     *   |     |     |-- user2Folder2
     *   |     |-- user2Folder3
     *   |     |     |-- user2File3
     *
     * </pre>
     */
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    nuxeoDriveManager.registerSynchronizationRoot(session1.getPrincipal(), user1Folder3, session1);
    nuxeoDriveManager.registerSynchronizationRoot(session1.getPrincipal(), user1Folder4, session1);
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    // --------------------------------------------
    // Check user synchronization roots
    // --------------------------------------------
    userSyncRootsJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", userSyncRootParent.getId())
                .execute();

    userSyncRoots = mapper.readValue(userSyncRootsJSON.getStream(), ArrayNode.class);
    assertNotNull(userSyncRoots);
    assertEquals(2, userSyncRoots.size());

    // user1Folder3
    folderItem = mapper.readValue(userSyncRoots.get(0), DocumentBackedFolderItem.class);
    checkFolderItem(
        folderItem,
        SYNC_ROOT_ID_PREFIX,
        user1Folder3,
        userWorkspace1ItemId,
        userWorkspace1ItemPath,
        "user1Folder3",
        "user1",
        "user1");
    folderItemChildrenJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", folderItem.getId())
                .execute();
    folderItemChildren = mapper.readValue(folderItemChildrenJSON.getStream(), ArrayNode.class);
    assertNotNull(folderItemChildren);
    assertEquals(1, folderItemChildren.size());
    // user1File3
    childFileItem = mapper.readValue(folderItemChildren.get(0), DocumentBackedFileItem.class);
    checkFileItem(
        childFileItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        user1File3,
        folderItem.getId(),
        folderItem.getPath(),
        "user1File3.txt",
        "user1",
        "user1");
    // user1Folder4
    folderItem = mapper.readValue(userSyncRoots.get(1), DocumentBackedFolderItem.class);
    checkFolderItem(
        folderItem,
        SYNC_ROOT_ID_PREFIX,
        user1Folder4,
        userWorkspace1ItemId,
        userWorkspace1ItemPath,
        "user1Folder4",
        "user1",
        "user1");

    /**
     *
     *
     * <pre>
     * =======================================================
     * Unregister a shared folder: user2Folder1
     * =======================================================
     * => Expected client side for user1:
     *
     * Nuxeo Drive
     *   |-- My Docs (unchanged)
     *   |     |-- user1Folder3
     *   |     |      |-- user1File3
     *   |     |-- user1Folder4
     *   |
     *   |-- Other Docs
     *   |     |-- user2Folder3
     *   |     |     |-- user2File3
     *
     * </pre>
     */
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    nuxeoDriveManager.unregisterSynchronizationRoot(
        session1.getPrincipal(), session1.getDocument(user2Folder1.getRef()), session1);
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    // ---------------------------------------------
    // Check shared synchronization roots
    // ---------------------------------------------
    sharedSyncRootsJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", sharedSyncRootParent.getId())
                .execute();

    sharedSyncRoots =
        mapper.readValue(
            sharedSyncRootsJSON.getStream(),
            new TypeReference<List<DefaultSyncRootFolderItem>>() {});
    assertNotNull(sharedSyncRoots);
    assertEquals(1, sharedSyncRoots.size());

    // user2Folder3
    sharedSyncRoot = sharedSyncRoots.get(0);
    checkFolderItem(
        sharedSyncRoot,
        SYNC_ROOT_ID_PREFIX,
        session1.getDocument(user2Folder3.getRef()),
        sharedSyncRootParent.getId(),
        sharedSyncRootParent.getPath(),
        "user2Folder3",
        "user2",
        "user1");
    sharedSyncRootChildrenJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", sharedSyncRoot.getId())
                .execute();
    sharedSyncRootChildren =
        mapper.readValue(sharedSyncRootChildrenJSON.getStream(), ArrayNode.class);
    assertNotNull(sharedSyncRootChildren);
    assertEquals(1, sharedSyncRootChildren.size());
    // user2File3
    sharedSyncRootChildFileItem =
        mapper.readValue(sharedSyncRootChildren.get(0), DocumentBackedFileItem.class);
    checkFileItem(
        sharedSyncRootChildFileItem,
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX,
        session1.getDocument(user2File3.getRef()),
        sharedSyncRoot.getId(),
        sharedSyncRoot.getPath(),
        "user2File3.txt",
        "user2",
        "user2");

    /**
     *
     *
     * <pre>
     * =======================================================
     * Remove permission on a shared folder: user2Folder3
     * =======================================================
     * => Expected client side for user1:
     *
     * Nuxeo Drive
     *   |-- My Docs (unchanged)
     *   |     |-- user1Folder3
     *   |     |      |-- user1File3
     *   |     |-- user1Folder4
     *   |
     *   |-- Other Docs
     *
     * </pre>
     */
    resetPermissions(user2Folder3.getRef(), "user1");

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    // ---------------------------------------------
    // Check shared synchronization roots
    // ---------------------------------------------
    sharedSyncRootsJSON =
        (Blob)
            clientSession1
                .newRequest(NuxeoDriveGetChildren.ID)
                .set("id", sharedSyncRootParent.getId())
                .execute();

    sharedSyncRoots =
        mapper.readValue(
            sharedSyncRootsJSON.getStream(),
            new TypeReference<List<DefaultSyncRootFolderItem>>() {});
    assertNotNull(sharedSyncRoots);
    assertEquals(0, sharedSyncRoots.size());
  }
  /**
   * Initializes the test hierarchy.
   *
   * <pre>
   * Server side for user1
   * ==============================
   *
   * /user1 (user workspace)
   *   |-- user1Folder1
   *   |     |-- user1File1
   *   |     |-- user1Folder2
   *   |-- user1File2
   *   |-- user1Folder3
   *   |     |-- user1File3
   *   |-- user1Folder4
   *
   * Server side for user2
   * ==============================
   *
   * /user2 (user workspace)
   *   |-- user2Folder1       (registered as a synchronization root with ReadWrite permission for user1)
   *   |     |-- user2File1
   *   |     |-- user2Folder2
   *   |-- user2File2
   *   |-- user2Folder3       (registered as a synchronization root with ReadWrite permission for user1)
   *   |     |-- user2File3
   *
   * </pre>
   */
  @Before
  public void init() throws Exception {

    // Create test users
    createUser("user1", "user1");
    createUser("user2", "user2");

    // Open a core session for each user
    session1 = coreFeature.openCoreSession("user1");
    session2 = coreFeature.openCoreSession("user2");

    // Create user workspace for each user
    userWorkspace1 = userWorkspaceService.getCurrentUserPersonalWorkspace(session1, null);
    userWorkspace2 = userWorkspaceService.getCurrentUserPersonalWorkspace(session2, null);

    userWorkspace1ItemId = USER_SYNC_ROOT_PARENT_ID_PREFIX + userWorkspace1.getId();
    userWorkspace1ItemPath = "/" + TOP_LEVEL_ID + "/" + userWorkspace1ItemId;

    // Populate user workspaces
    // user1
    user1Folder1 =
        createFolder(session1, userWorkspace1.getPathAsString(), "user1Folder1", "Folder");
    user1File1 =
        createFile(
            session1,
            user1Folder1.getPathAsString(),
            "user1File1",
            "File",
            "user1File1.txt",
            CONTENT_PREFIX + "user1File1");
    user1Folder2 = createFolder(session1, user1Folder1.getPathAsString(), "user1Folder2", "Folder");
    user1File2 =
        createFile(
            session1,
            userWorkspace1.getPathAsString(),
            "user1File2",
            "File",
            "user1File2.txt",
            CONTENT_PREFIX + "user1File2");
    user1Folder3 =
        createFolder(session1, userWorkspace1.getPathAsString(), "user1Folder3", "Folder");
    user1File3 =
        createFile(
            session1,
            user1Folder3.getPathAsString(),
            "user1File3",
            "File",
            "user1File3.txt",
            CONTENT_PREFIX + "user1File3");
    user1Folder4 =
        createFolder(session1, userWorkspace1.getPathAsString(), "user1Folder4", "Folder");
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    // user2
    user2Folder1 =
        createFolder(session2, userWorkspace2.getPathAsString(), "user2Folder1", "Folder");
    user2File1 =
        createFile(
            session2,
            user2Folder1.getPathAsString(),
            "user2File1",
            "File",
            "user2File1.txt",
            CONTENT_PREFIX + "user2File1");
    user2Folder2 = createFolder(session2, user2Folder1.getPathAsString(), "user2Folder2", "Folder");
    user2File2 =
        createFile(
            session2,
            userWorkspace2.getPathAsString(),
            "user2File2",
            "File",
            "user2File2.txt",
            CONTENT_PREFIX + "user2File2");
    user2Folder3 =
        createFolder(session2, userWorkspace2.getPathAsString(), "user2Folder3", "Folder");
    user2File3 =
        createFile(
            session2,
            user2Folder3.getPathAsString(),
            "user2File3",
            "File",
            "user2File3.txt",
            CONTENT_PREFIX + "user2File3");
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();
    setPermission(user2Folder1, "user1", SecurityConstants.READ_WRITE, true);
    setPermission(user2Folder3, "user1", SecurityConstants.READ_WRITE, true);

    // Register shared folders as synchronization roots for user1
    nuxeoDriveManager.registerSynchronizationRoot(
        session1.getPrincipal(), session1.getDocument(user2Folder1.getRef()), session1);
    nuxeoDriveManager.registerSynchronizationRoot(
        session1.getPrincipal(), session1.getDocument(user2Folder3.getRef()), session1);

    // Get an Automation client session for user1
    clientSession1 = automationClient.getSession("user1", "user1");

    mapper = new ObjectMapper();
  }
  @Test
  public void testReadOperations() throws Exception {

    // ------------------------------------------------------
    // Check #getTopLevelFolder
    // ------------------------------------------------------
    List<FileSystemItem> topLevelChildren =
        fileSystemItemManagerService.getTopLevelFolder(principal).getChildren();
    assertNotNull(topLevelChildren);
    assertEquals(2, topLevelChildren.size());

    FileSystemItem childFsItem = topLevelChildren.get(0);
    assertTrue(childFsItem instanceof DefaultSyncRootFolderItem);
    assertEquals("defaultSyncRootFolderItemFactory#test#" + syncRoot1.getId(), childFsItem.getId());
    assertTrue(childFsItem.getParentId().endsWith("DefaultTopLevelFolderItemFactory#"));
    assertEquals("syncRoot1", childFsItem.getName());

    childFsItem = topLevelChildren.get(1);
    assertTrue(childFsItem instanceof DefaultSyncRootFolderItem);
    assertEquals("defaultSyncRootFolderItemFactory#test#" + syncRoot2.getId(), childFsItem.getId());
    assertTrue(childFsItem.getParentId().endsWith("DefaultTopLevelFolderItemFactory#"));
    assertEquals("syncRoot2", childFsItem.getName());

    // ------------------------------------------------------
    // Check #exists
    // ------------------------------------------------------
    // Non existent doc id
    assertFalse(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + "nonExistentId", principal));
    // File
    assertTrue(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), principal));
    // Not adaptable as a FileSystemItem
    assertFalse(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + notAFileSystemItem.getId(), principal));
    // Deleted
    custom.followTransition("delete");
    assertFalse(
        fileSystemItemManagerService.exists(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + custom.getId(), principal));

    // ------------------------------------------------------------
    // Check #getFileSystemItemById(String id, Principal principal)
    // ------------------------------------------------------------
    // Folder
    FileSystemItem fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getId());
    String expectedSyncRoot1Id = DEFAULT_SYNC_ROOT_ITEM_ID_PREFIX + syncRoot1.getId();
    assertEquals(expectedSyncRoot1Id, fsItem.getParentId());
    assertEquals("Jack's folder", fsItem.getName());
    assertTrue(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    assertTrue(((FolderItem) fsItem).getCanCreateChild());
    List<FileSystemItem> children = ((FolderItem) fsItem).getChildren();
    assertNotNull(children);
    assertEquals(4, children.size());

    // File
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FileItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("Joe.odt", fsItem.getName());
    assertFalse(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    FileItem fileFsItem = (FileItem) fsItem;
    assertTrue(fileFsItem.getCanUpdate());
    assertEquals(
        "nxfile/test/" + file.getId() + "/blobholder:0/Joe.odt", fileFsItem.getDownloadURL());
    assertEquals("MD5", fileFsItem.getDigestAlgorithm());
    assertEquals(file.getAdapter(BlobHolder.class).getBlob().getDigest(), fileFsItem.getDigest());
    Blob fileItemBlob = fileFsItem.getBlob();
    assertEquals("Joe.odt", fileItemBlob.getFilename());
    assertEquals("Content of Joe's file.", fileItemBlob.getString());

    // FolderishFile
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folderishFile.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folderishFile.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("Sarah's folderish file", fsItem.getName());
    assertTrue(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    assertTrue(((FolderItem) fsItem).getCanCreateChild());
    assertTrue(((FolderItem) fsItem).getChildren().isEmpty());

    // Not adaptable as a FileSystemItem
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + notAFileSystemItem.getId(), principal);
    assertNull(fsItem);

    // Deleted
    assertNull(
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + custom.getId(), principal));

    // Sub folder
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), principal);
    assertNotNull(fsItem);
    assertTrue(fsItem instanceof FolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("Tony's sub folder", fsItem.getName());
    assertTrue(fsItem.isFolder());
    assertTrue(fsItem.getCanRename());
    assertTrue(fsItem.getCanDelete());
    assertTrue(((FolderItem) fsItem).getCanCreateChild());
    assertTrue(((FolderItem) fsItem).getChildren().isEmpty());

    // -------------------------------------------------------------------
    // Check #getFileSystemItemById(String id, String parentId, Principal
    // principal)
    // -------------------------------------------------------------------
    fsItem =
        fileSystemItemManagerService.getFileSystemItemById(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(),
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(),
            principal);
    assertTrue(fsItem instanceof FileItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());

    // ------------------------------------------------------
    // Check #getChildren
    // ------------------------------------------------------
    // Need to flush VCS cache for the session used in DocumentBackedFolderItem#getChildren() to be
    // aware of changes
    // in the current session
    session.save();
    children =
        fileSystemItemManagerService.getChildren(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal);
    assertNotNull(children);

    assertEquals(4, children.size());
    // Ordered
    checkChildren(
        children,
        folder.getId(),
        file.getId(),
        note.getId(),
        folderishFile.getId(),
        subFolder.getId(),
        true);

    children =
        fileSystemItemManagerService.getChildren(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), principal);
    assertTrue(children.isEmpty());

    // ------------------------------------------------------
    // Check #scrollDescendants
    // ------------------------------------------------------
    // Need to flush VCS cache for the session used in DocumentBackedFolderItem#scrollDescendants to
    // be aware of
    // changes in the current session
    session.save();
    FolderItem folderItem =
        (FolderItem)
            fileSystemItemManagerService.getFileSystemItemById(
                DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal);
    assertTrue(folderItem.getCanScrollDescendants());

    // Scroll through all descendants in one breath
    ScrollFileSystemItemList folderDescendants =
        fileSystemItemManagerService.scrollDescendants(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal, null, 10, 1000);
    assertNotNull(folderDescendants);
    assertNotNull(folderDescendants.getScrollId());
    assertEquals(4, folderDescendants.size());
    // Order is not determined
    checkChildren(
        folderDescendants,
        folder.getId(),
        file.getId(),
        note.getId(),
        folderishFile.getId(),
        subFolder.getId(),
        false);

    // Scroll through descendants in several steps
    folderDescendants.clear();
    ScrollFileSystemItemList descendantsBatch;
    int batchSize = 2;
    String scrollId = null;
    while (!(descendantsBatch = folderItem.scrollDescendants(scrollId, batchSize, 1000))
        .isEmpty()) {
      assertTrue(descendantsBatch.size() > 0);
      scrollId = descendantsBatch.getScrollId();
      folderDescendants.addAll(descendantsBatch);
    }
    assertEquals(4, folderDescendants.size());
    // Order is not determined
    checkChildren(
        folderDescendants,
        folder.getId(),
        file.getId(),
        note.getId(),
        folderishFile.getId(),
        subFolder.getId(),
        false);

    folderDescendants =
        fileSystemItemManagerService.scrollDescendants(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId(), principal, null, 10, 1000);
    assertTrue(folderDescendants.isEmpty());

    // ------------------------------------------------------
    // Check #canMove
    // ------------------------------------------------------
    // Not allowed to move a file system item to a non FolderItem
    String srcFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + note.getId();
    String destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId();
    assertFalse(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, principal));

    // Not allowed to move a file system item if no REMOVE permission on the
    // source backing doc
    Principal joePrincipal = new NuxeoPrincipalImpl("joe");
    DocumentModel rootDoc = session.getRootDocument();
    setPermission(rootDoc, "joe", SecurityConstants.READ, true);
    nuxeoDriveManager.registerSynchronizationRoot(joePrincipal, syncRoot1, session);

    // Under Oracle, the READ ACL optims are not visible from the joe
    // session while the transaction has not been committed.
    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId();
    assertFalse(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, joePrincipal));

    // Not allowed to move a file system item if no ADD_CHILDREN permission
    // on the destination backing doc
    setPermission(folder, "joe", SecurityConstants.WRITE, true);
    setPermission(subFolder, "joe", SecurityConstants.READ, true);
    setPermission(subFolder, SecurityConstants.ADMINISTRATOR, SecurityConstants.EVERYTHING, true);
    setPermission(subFolder, SecurityConstants.EVERYONE, SecurityConstants.EVERYTHING, false);
    assertFalse(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, joePrincipal));

    // OK: REMOVE permission on the source backing doc + REMOVE_CHILDREN
    // permission on its parent + ADD_CHILDREN permission on the destination
    // backing doc
    resetPermissions(subFolder, SecurityConstants.EVERYONE);
    resetPermissions(subFolder, "joe");
    setPermission(subFolder, "joe", SecurityConstants.WRITE, true);
    assertTrue(fileSystemItemManagerService.canMove(srcFsItemId, destFsItemId, joePrincipal));

    // Reset permissions
    resetPermissions(rootDoc, "joe");
    resetPermissions(folder, "joe");
    resetPermissions(subFolder, "joe");
  }
Пример #19
0
  @Test
  public void shouldHandlePagination() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    List<LogEntry> logEntries = new ArrayList<>();
    LogEntry logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("secondEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("thirdEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("fourthEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("fifthEvent");
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("sixthEvent");
    logEntries.add(logEntry);
    auditLogger.addLogEntries(logEntries);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(6, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.putSingle("currentPageIndex", "0");
    queryParams.putSingle("pageSize", "2");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    assertTrue(node.get("isPaginable").getBooleanValue());
    assertEquals(0, node.get("currentPageIndex").getIntValue());
    assertEquals(2, node.get("pageSize").getIntValue());
    assertEquals(3, node.get("numberOfPages").getIntValue());
    nodes = getLogEntries(node);
    assertEquals(2, nodes.size());
    assertEquals("sixthEvent", nodes.get(0).get("eventId").getValueAsText());
    assertEquals("fifthEvent", nodes.get(1).get("eventId").getValueAsText());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.putSingle("currentPageIndex", "1");
    queryParams.putSingle("pageSize", "3");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    assertTrue(node.get("isPaginable").getBooleanValue());
    assertEquals(1, node.get("currentPageIndex").getIntValue());
    assertEquals(3, node.get("pageSize").getIntValue());
    assertEquals(2, node.get("numberOfPages").getIntValue());
    nodes = getLogEntries(node);
    assertEquals(3, nodes.size());
    assertEquals("thirdEvent", nodes.get(0).get("eventId").getValueAsText());
    assertEquals("secondEvent", nodes.get(1).get("eventId").getValueAsText());
    assertEquals("firstEvent", nodes.get(2).get("eventId").getValueAsText());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.putSingle("currentPageIndex", "2");
    queryParams.putSingle("pageSize", "3");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertTrue(node.get("isPaginable").getBooleanValue());
    assertEquals(0, nodes.size());
  }
Пример #20
0
  @Test
  public void shouldFilterLogEntriesOnMultipleCriteria() throws Exception {
    DocumentModel doc = RestServerInit.getFile(1, session);

    DateTime firstDate = new DateTime();
    DateTime secondDate = firstDate.plusDays(10);

    List<LogEntry> logEntries = new ArrayList<>();
    LogEntry logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntry.setPrincipalName("bender");
    logEntry.setEventDate(firstDate.toDate());
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("secondEvent");
    logEntry.setPrincipalName("leela");
    logEntry.setEventDate(firstDate.toDate());
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("firstEvent");
    logEntry.setPrincipalName("leela");
    logEntry.setEventDate(secondDate.toDate());
    logEntries.add(logEntry);
    logEntry = auditLogger.newLogEntry();
    logEntry.setDocUUID(doc.getRef());
    logEntry.setCategory("One");
    logEntry.setEventId("thirdEvent");
    logEntry.setPrincipalName("leela");
    logEntry.setEventDate(secondDate.toDate());
    logEntries.add(logEntry);
    auditLogger.addLogEntries(logEntries);

    TransactionHelper.commitOrRollbackTransaction();
    TransactionHelper.startTransaction();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.add("principalName", "leela");
    ClientResponse response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    List<JsonNode> nodes = getLogEntries(node);
    assertEquals(3, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.add("principalName", "leela");
    queryParams.add("eventId", "thirdEvent");
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(1, nodes.size());

    queryParams = new MultivaluedMapImpl();
    queryParams.putSingle("category", "One");
    queryParams.add("principalName", "leela");
    queryParams.add("eventId", "thirdEvent");
    queryParams.add("startEventDate", ISODateTimeFormat.date().print(firstDate.plusDays(1)));
    queryParams.add("endEventDate", ISODateTimeFormat.date().print(secondDate.minus(1)));
    response =
        getResponse(
            BaseTest.RequestType.GET, "id/" + doc.getId() + "/@" + AuditAdapter.NAME, queryParams);
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    node = mapper.readTree(response.getEntityInputStream());
    nodes = getLogEntries(node);
    assertEquals(0, nodes.size());
  }