/**
   * Añade un hijo al arbol.
   *
   * @param result XML resultado
   * @param parent Elemento padre del xml
   * @param root Documento raíz.
   * @param depth profundidad
   * @return devuelve un elemento XML
   */
  private Element addChildren(DOMDocument result, Element parent, DocumentModel root, int depth) {
    try {

      List<DocumentModel> hijos = documentManager.getChildren(root.getRef());

      for (DocumentModel documento : hijos) {
        String estado = documento.getCurrentLifeCycleState();
        if (!"deleted".equals(estado) && documento.isFolder()) {
          Element hijo = result.createElement("document");

          hijo.setAttribute("title", documento.getTitle());
          hijo.setAttribute("type", documento.getType());
          hijo.setAttribute("id", documento.getId());

          parent.appendChild(hijo);

          if (depth > ArchivoConstantes.NUMERO_UNO) {
            addChildren(result, hijo, documento, depth - ArchivoConstantes.NUMERO_UNO);
          }
        }
      }
    } catch (ClientException e) {
      LOG.error("No se pudo a&ntilde;adir elementos al xml ", e);
    }
    return parent;
  }
  @Test
  public void testAddManyDocsToNewCollectionAndRemove() throws ClientException {
    DocumentModel testWorkspace =
        session.createDocumentModel("/default-domain/workspaces", "testWorkspace", "Workspace");
    testWorkspace = session.createDocument(testWorkspace);

    List<DocumentModel> files = createTestFiles(session, 3);

    collectionManager.addToNewCollection(COLLECTION_NAME, COLLECTION_DESCRIPTION, files, session);

    assertTrue(session.exists(new PathRef(COLLECTION_FOLDER_PATH)));

    final String newlyCreatedCollectionPath = COLLECTION_FOLDER_PATH + "/" + COLLECTION_NAME;

    DocumentRef newCollectionRef = new PathRef(newlyCreatedCollectionPath);
    assertTrue(session.exists(newCollectionRef));

    DocumentModel newlyCreatedCollection = session.getDocument(newCollectionRef);
    final String newlyCreatedCollectionId = newlyCreatedCollection.getId();

    assertEquals(COLLECTION_NAME, newlyCreatedCollection.getTitle());

    assertEquals(
        COLLECTION_DESCRIPTION, newlyCreatedCollection.getProperty("dc:description").getValue());

    for (DocumentModel file : files) {
      file = session.getDocument(file.getRef());

      Collection collectionAdapter = newlyCreatedCollection.getAdapter(Collection.class);

      assertTrue(collectionAdapter.getCollectedDocumentIds().contains(file.getId()));

      CollectionMember collectionMemberAdapter = file.getAdapter(CollectionMember.class);

      assertTrue(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));
    }

    collectionManager.removeAllFromCollection(newlyCreatedCollection, files, session);

    for (DocumentModel file : files) {
      Collection collectionAdapter = newlyCreatedCollection.getAdapter(Collection.class);

      assertFalse(collectionAdapter.getCollectedDocumentIds().contains(file.getId()));

      CollectionMember collectionMemberAdapter = file.getAdapter(CollectionMember.class);

      assertFalse(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));
    }
  }
 public static Suggestion fromDocumentModel(DocumentModel doc) {
   TypeInfo typeInfo = doc.getAdapter(TypeInfo.class);
   String description = doc.getProperty("dc:description").getValue(String.class);
   String icon = null;
   if (doc.hasSchema("common")) {
     icon = (String) doc.getProperty("common", "icon");
   }
   if (StringUtils.isEmpty(icon)) {
     icon = typeInfo.getIcon();
   }
   String thumbnailURL = String.format("api/v1/id/%s/@rendition/thumbnail", doc.getId());
   return new DocumentSuggestion(doc.getId(), new DocumentLocationImpl(doc), doc.getTitle(), icon)
       .withDescription(description)
       .withThumbnailURL(thumbnailURL);
 }
  @Test
  public void testAddOneDocToNewCollectionAndRemove() throws Exception {
    DocumentModel testWorkspace =
        session.createDocumentModel("/default-domain/workspaces", "testWorkspace", "Workspace");
    testWorkspace = session.createDocument(testWorkspace);
    DocumentModel testFile =
        session.createDocumentModel(testWorkspace.getPathAsString(), TEST_FILE_NAME, "File");
    testFile = session.createDocument(testFile);
    collectionManager.addToNewCollection(
        COLLECTION_NAME, COLLECTION_DESCRIPTION, testFile, session);

    assertTrue(session.exists(new PathRef(COLLECTION_FOLDER_PATH)));

    final String newlyCreatedCollectionPath = COLLECTION_FOLDER_PATH + "/" + COLLECTION_NAME;

    DocumentRef newCollectionRef = new PathRef(newlyCreatedCollectionPath);
    assertTrue(session.exists(newCollectionRef));

    DocumentModel newlyCreatedCollection = session.getDocument(newCollectionRef);
    final String newlyCreatedCollectionId = newlyCreatedCollection.getId();

    assertEquals(COLLECTION_NAME, newlyCreatedCollection.getTitle());

    assertEquals(
        COLLECTION_DESCRIPTION, newlyCreatedCollection.getProperty("dc:description").getValue());

    Collection collectionAdapter = newlyCreatedCollection.getAdapter(Collection.class);

    assertTrue(collectionAdapter.getCollectedDocumentIds().contains(testFile.getId()));

    testFile = session.getDocument(testFile.getRef());

    CollectionMember collectionMemberAdapter = testFile.getAdapter(CollectionMember.class);

    assertTrue(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));

    collectionManager.removeFromCollection(newlyCreatedCollection, testFile, session);

    assertFalse(collectionAdapter.getCollectedDocumentIds().contains(testFile.getId()));
    assertFalse(collectionMemberAdapter.getCollectionIds().contains(newlyCreatedCollectionId));
  }
  @Test
  public void testIntegrationTestsSetupAndTearDown() throws Exception {

    // ---------------------------------------------------------
    // Setup the integration tests environment as Administrator
    // ---------------------------------------------------------
    Blob testUserCredentialsBlob =
        (Blob)
            clientSession
                .newRequest(NuxeoDriveSetupIntegrationTests.ID)
                .set("userNames", "joe,jack")
                .execute();
    assertNotNull(testUserCredentialsBlob);

    // Check test users
    String testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8");
    assertNotNull(testUserCredentials);
    String[] testUserCrendentialsArray = StringUtils.split(testUserCredentials, ",");
    assertEquals(2, testUserCrendentialsArray.length);
    assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_joe:"));
    assertTrue(testUserCrendentialsArray[1].startsWith("nuxeoDriveTestUser_jack:"));

    // useMembersGroup is false by default
    NuxeoPrincipal joePrincipal = userManager.getPrincipal("nuxeoDriveTestUser_joe");
    assertNotNull(joePrincipal);
    assertFalse(joePrincipal.getGroups().contains("members"));
    NuxeoPrincipal jackPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_jack");
    assertNotNull(jackPrincipal);
    assertFalse(jackPrincipal.getGroups().contains("members"));

    // Check test workspace
    DocumentRef testWorkspaceRef = new PathRef(TEST_WORKSPACE_PATH);
    DocumentModel testWorkspace = session.getDocument(testWorkspaceRef);
    assertEquals("Workspace", testWorkspace.getType());
    assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle());
    assertTrue(session.hasPermission(joePrincipal, testWorkspaceRef, SecurityConstants.WRITE));
    assertTrue(session.hasPermission(jackPrincipal, testWorkspaceRef, SecurityConstants.WRITE));

    // Create test users' personal workspaces for cleanup check
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_joe", session.getRootDocument());
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_jack", session.getRootDocument());
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe")));
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack")));

    // ----------------------------------------------------------------------
    // Setup the integration tests environment with other user names without
    // having teared it down previously => should start by cleaning it up
    // ----------------------------------------------------------------------
    testUserCredentialsBlob =
        (Blob)
            clientSession
                .newRequest(NuxeoDriveSetupIntegrationTests.ID)
                .set("userNames", "sarah")
                .set("useMembersGroup", true)
                .execute();
    assertNotNull(testUserCredentialsBlob);

    // Check cleanup
    assertNull(userManager.getPrincipal("nuxeoDriveTestUser_joe"));
    assertNull(userManager.getPrincipal("nuxeoDriveTestUser_jack"));
    // Invalid VCS cache
    session.save();
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-joe",
          e.getMessage());
    }
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-jack",
          e.getMessage());
    }

    // Check test users
    testUserCredentials = IOUtils.toString(testUserCredentialsBlob.getStream(), "UTF-8");
    assertNotNull(testUserCredentials);
    testUserCrendentialsArray = StringUtils.split(testUserCredentials, ",");
    assertEquals(1, testUserCrendentialsArray.length);
    assertTrue(testUserCrendentialsArray[0].startsWith("nuxeoDriveTestUser_sarah:"));

    NuxeoPrincipal sarahPrincipal = userManager.getPrincipal("nuxeoDriveTestUser_sarah");
    assertNotNull(sarahPrincipal);
    assertTrue(sarahPrincipal.getGroups().contains("members"));

    // Check test workspace
    testWorkspace = session.getDocument(testWorkspaceRef);
    assertEquals("Nuxeo Drive Test Workspace", testWorkspace.getTitle());
    assertTrue(session.hasPermission(sarahPrincipal, testWorkspaceRef, SecurityConstants.WRITE));

    // Create test users' personal workspaces for cleanup check
    userWorkspaceService.getUserPersonalWorkspace(
        "nuxeoDriveTestUser_sarah", session.getRootDocument());
    assertNotNull(
        session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah")));

    // ----------------------------------------------------------------------
    // Try to setup the integration tests environment as an unauthorized
    // user => should fail
    // ----------------------------------------------------------------------
    Session unauthorizedSession =
        automationClient.getSession("nuxeoDriveTestUser_sarah", testUserCrendentialsArray[0]);
    try {
      unauthorizedSession
          .newRequest(NuxeoDriveSetupIntegrationTests.ID)
          .set("userNames", "john,bob")
          .execute();
      fail(
          "NuxeoDrive.SetupIntegrationTests operation should not be callable by a non administrator.");
    } catch (Exception e) {
      // Expected
    }

    // ----------------------------------------------------------------------
    // Try to tear down the integration tests environment as an unauthorized
    // user => should fail
    // ----------------------------------------------------------------------
    try {
      unauthorizedSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute();
      fail(
          "NuxeoDrive.TearDownIntegrationTests operation should not be callable by a non administrator.");
    } catch (Exception e) {
      // Expected
    }

    // ----------------------------------------------------------------------
    // Tear down the integration tests environment as Administrator
    // ----------------------------------------------------------------------
    clientSession.newRequest(NuxeoDriveTearDownIntegrationTests.ID).execute();
    assertTrue(userManager.searchUsers("nuxeoDriveTestUser_").isEmpty());
    // Invalid VCS cache
    session.save();
    try {
      session.getDocument(new PathRef(USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah"));
      fail("User workspace should not exist.");
    } catch (ClientException e) {
      assertEquals(
          "Failed to get document " + USER_WORKSPACE_PARENT_PATH + "/nuxeoDriveTestUser-sarah",
          e.getMessage());
    }
    assertFalse(session.exists(testWorkspaceRef));
  }
  /**
   * Manejador principal del restlet.
   *
   * @param req Request
   * @param res Response
   */
  @Override
  public void handle(Request req, Response res) {
    /* Conflicto con Checkstyle. No se pueden declarar como final los m&eacute;todos de
     * beans EJB que hagan uso de dependencias inyectadas, ya que dichas
     * dependencias toman el valor null.
     * No se declara como final debido a que en ese caso
     * la inyecci&oacute;n de dependencias dejar&iacute;a de funcionar.
     */
    String repo = (String) req.getAttributes().get("repo");
    String cdcDocId = (String) req.getAttributes().get("docid");
    if (cdcDocId == null) {
      handleError(res, "you must specify a CdC source document Id.");
    } else {
      String depth = getQueryParamValue(req, "depth", "1");

      if (repo == null || repo.equals("*")) {
        handleError(res, "you must specify a repository");
      } else {

        int profundidad = Integer.parseInt(depth);
        // String cdcPath =
        // Framework.getProperty(ArchivoConstantes.PROPIEDAD_CDC_PATH);
        DOMDocumentFactory domFactory = new DOMDocumentFactory();
        DOMDocument result = (DOMDocument) domFactory.createDocument();
        try {

          navigationContext.setCurrentServerLocation(new RepositoryLocation(repo));
          documentManager = navigationContext.getOrCreateDocumentManager();
          DocumentModel cdcRoot = documentManager.getDocument(new IdRef(cdcDocId));
          if (cdcRoot != null) {
            Element current = result.createElement("document");

            current.setAttribute("title", cdcRoot.getTitle());
            current.setAttribute("type", cdcRoot.getType());
            current.setAttribute("id", cdcRoot.getId());
            current.setAttribute("path", cdcRoot.getPathAsString());

            result.setRootElement((org.dom4j.Element) current);

            addChildren(result, current, cdcRoot, profundidad);
          } else {
            Element noEncontrado = result.createElement("cdCNoRegistrado");
            noEncontrado.setAttribute("variable", ArchivoConstantes.PROPIEDAD_CDC_PATH);
            noEncontrado.setAttribute("valor", cdcDocId);
            result.setRootElement((org.dom4j.Element) noEncontrado);
            LOG.error(
                "No se ha configurado la ruta del CdC; por favor configure la ruta en la propiedad "
                    + ArchivoConstantes.PROPIEDAD_CDC_PATH);
          }

          res.setEntity(result.asXML(), MediaType.TEXT_XML);
          res.getEntity().setCharacterSet(CharacterSet.UTF_8);

        }
        /**
         * Conflicto con checkstyle. Es necesario capturar la excepci&oacute;n Exception, dado que
         * el c&oacute;digo nativo de Nuxeo lanza dicha excepci&oacute;n. En caso contrario, este
         * c&oacute;digo no compilar&iacute;a
         */
        catch (Exception e) {
          LOG.error(e);
          handleError(res, e);
        }
      }
    }
  }
 public String getTitle() {
   return folder.getTitle();
 }
Beispiel #8
0
  @Override
  protected void doHandleStatelessRequest(Request req, Response res) {
    String repo = (String) req.getAttributes().get("repo");
    String docid = (String) req.getAttributes().get("docid");

    DOMDocumentFactory domFactory = new DOMDocumentFactory();

    DOMDocument result = (DOMDocument) domFactory.createDocument();

    if (repo == null || repo.equals("*")) {
      try {
        Element serversNode = result.createElement("avalaibleServers");
        result.setRootElement((org.dom4j.Element) serversNode);

        RepositoryManager repositoryManager = Framework.getLocalService(RepositoryManager.class);
        for (String repositoryName : repositoryManager.getRepositoryNames()) {
          Element server = result.createElement("server");
          server.setAttribute("title", repositoryName);
          server.setAttribute("url", getRelURL(repositoryName, "*"));
          serversNode.appendChild(server);
        }
        res.setEntity(result.asXML(), MediaType.TEXT_XML);
        res.getEntity().setCharacterSet(CharacterSet.UTF_8);
        return;
      } catch (DOMException e) {
        handleError(result, res, e);
        return;
      }
    } else {
      DocumentModel dm;

      boolean init = initRepository(res, repo);
      boolean isRoot = false;
      try {
        if (init) {
          if (docid == null || docid.equals("*")) {
            dm = session.getRootDocument();
            isRoot = true;
          } else {
            dm = session.getDocument(new IdRef(docid));
          }
        } else {
          handleError(res, "Unable to init repository");
          return;
        }
      } catch (NuxeoException e) {
        handleError(res, e);
        return;
      }

      Element current = result.createElement("document");
      try {
        current.setAttribute("title", dm.getTitle());
      } catch (DOMException | NuxeoException e) {
        handleError(res, e);
      }
      current.setAttribute("type", dm.getType());
      current.setAttribute("id", dm.getId());
      current.setAttribute("name", dm.getName());
      if (isRoot) {
        current.setAttribute("url", getRelURL(repo, ""));
      } else {
        current.setAttribute("url", getRelURL(repo, dm.getRef().toString()));
      }
      result.setRootElement((org.dom4j.Element) current);

      if (dm.isFolder()) {
        // Element childrenElem = result.createElement("children");
        // root.appendChild(childrenElem);

        DocumentModelList children;
        try {
          children = session.getChildren(dm.getRef());
        } catch (NuxeoException e) {
          handleError(result, res, e);
          return;
        }

        for (DocumentModel child : children) {
          Element el = result.createElement("document");
          try {
            el.setAttribute("title", child.getTitle());
          } catch (DOMException e) {
            handleError(res, e);
          } catch (NuxeoException e) {
            handleError(res, e);
          }
          el.setAttribute("type", child.getType());
          el.setAttribute("id", child.getId());
          el.setAttribute("name", child.getName());
          el.setAttribute("url", getRelURL(repo, child.getRef().toString()));
          current.appendChild(el);
        }
      }

      res.setEntity(result.asXML(), MediaType.TEXT_XML);
      res.getEntity().setCharacterSet(CharacterSet.UTF_8);
    }
  }
  @Test
  public void testWriteOperations() throws Exception {

    // ------------------------------------------------------
    // Check #createFolder
    // ------------------------------------------------------
    // Not allowed to create a folder in a non FolderItem
    try {
      fileSystemItemManagerService.createFolder(
          DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(), "A new folder", principal);
      fail("Folder creation in a non folder item should fail.");
    } catch (NuxeoException e) {
      assertEquals(
          String.format(
              "Cannot create a folder in file system item with id %s because it is not a folder but is: "
                  + "DocumentBackedFileItem(id=\"%s\", name=\"Joe.odt\")",
              DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId(),
              DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId()),
          e.getMessage());
    }

    // Folder creation
    FolderItem newFolderItem =
        fileSystemItemManagerService.createFolder(
            DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), "A new folder", principal);
    assertNotNull(newFolderItem);
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), newFolderItem.getParentId());
    assertEquals("A new folder", newFolderItem.getName());
    DocumentModelList folderChildren =
        session.query(
            String.format(
                "select * from Document where ecm:parentId = '%s' and ecm:primaryType = 'Folder' order by dc:title asc",
                folder.getId()));
    DocumentModel newFolder = folderChildren.get(0);
    assertTrue(newFolder.isFolder());
    assertEquals("A new folder", newFolder.getTitle());

    // Parent folder children check
    assertEquals(
        6,
        fileSystemItemManagerService
            .getChildren(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), principal)
            .size());

    // ------------------------------------------------------
    // Check #createFile
    // ------------------------------------------------------
    // File creation
    Blob blob = new StringBlob("Content of a new file.");
    blob.setFilename("New file.odt");
    blob.setMimeType("application/vnd.oasis.opendocument.text");
    FileItem fileItem =
        fileSystemItemManagerService.createFile(newFolderItem.getId(), blob, principal);
    assertNotNull(fileItem);
    assertEquals(newFolderItem.getId(), fileItem.getParentId());
    assertEquals("New file.odt", fileItem.getName());
    folderChildren =
        session.query(
            String.format("select * from Document where ecm:parentId = '%s'", newFolder.getId()));
    assertEquals(1, folderChildren.size());
    DocumentModel newFile = folderChildren.get(0);
    assertEquals("File", newFile.getType());
    assertEquals("New file.odt", newFile.getTitle());
    assertEquals("/syncRoot1/aFolder/A new folder/New file.odt", newFile.getPathAsString());
    Blob newFileBlob = (Blob) newFile.getPropertyValue("file:content");
    assertEquals("New file.odt", newFileBlob.getFilename());
    assertEquals("Content of a new file.", newFileBlob.getString());
    assertEquals(
        "nxfile/test/" + newFile.getId() + "/blobholder:0/New%20file.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(newFileBlob.getDigest(), fileItem.getDigest());

    // Parent folder children check
    assertEquals(
        1, fileSystemItemManagerService.getChildren(newFolderItem.getId(), principal).size());

    // ------------------------------------------------------
    // Check #updateFile
    // ------------------------------------------------------
    String fileItemId = fileItem.getId();
    String fileItemParentId = fileItem.getParentId();
    blob = new StringBlob("Modified content of an existing file.");
    fileItem = fileSystemItemManagerService.updateFile(fileItemId, blob, principal);
    assertNotNull(fileItem);
    assertEquals(fileItemId, fileItem.getId());
    assertEquals(fileItemParentId, fileItem.getParentId());
    assertEquals("New file.odt", fileItem.getName());
    folderChildren =
        session.query(
            String.format("select * from Document where ecm:parentId = '%s'", newFolder.getId()));
    assertEquals(1, folderChildren.size());
    DocumentModel updatedFile = folderChildren.get(0);
    assertEquals("File", updatedFile.getType());
    assertEquals("New file.odt", updatedFile.getTitle());
    assertEquals("/syncRoot1/aFolder/A new folder/New file.odt", updatedFile.getPathAsString());
    Blob updatedFileBlob = (Blob) updatedFile.getPropertyValue("file:content");
    assertEquals("New file.odt", updatedFileBlob.getFilename());
    assertEquals("Modified content of an existing file.", updatedFileBlob.getString());
    assertEquals(
        "nxfile/test/" + updatedFile.getId() + "/blobholder:0/New%20file.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(updatedFileBlob.getDigest(), fileItem.getDigest());

    // ------------------------------------------------------
    // Check #delete
    // ------------------------------------------------------
    // File deletion
    fileSystemItemManagerService.delete(
        DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + updatedFile.getId(), principal);
    updatedFile = session.getDocument(new IdRef(updatedFile.getId()));
    assertEquals("deleted", updatedFile.getCurrentLifeCycleState());

    // Parent folder children check
    assertTrue(
        fileSystemItemManagerService.getChildren(newFolderItem.getId(), principal).isEmpty());

    // ------------------------------------------------------
    // Check #rename
    // ------------------------------------------------------
    // Folder rename
    String fsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId();
    FileSystemItem fsItem =
        fileSystemItemManagerService.rename(fsItemId, "Jack's folder has a new name", principal);
    assertEquals(fsItemId, fsItem.getId());
    String expectedSyncRoot1Id = DEFAULT_SYNC_ROOT_ITEM_ID_PREFIX + syncRoot1.getId();
    assertEquals(expectedSyncRoot1Id, fsItem.getParentId());
    assertEquals("Jack's folder has a new name", fsItem.getName());
    folder = session.getDocument(folder.getRef());
    assertEquals("Jack's folder has a new name", folder.getTitle());

    // File rename with title != filename
    // => should rename filename but not title
    assertEquals("aFile", file.getTitle());
    assertEquals("Joe.odt", ((Blob) file.getPropertyValue("file:content")).getFilename());
    fsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId();
    fsItem = fileSystemItemManagerService.rename(fsItemId, "File new name.odt", principal);
    assertEquals(fsItemId, fsItem.getId());
    assertEquals(DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + folder.getId(), fsItem.getParentId());
    assertEquals("File new name.odt", fsItem.getName());
    file = session.getDocument(file.getRef());
    assertEquals("aFile", file.getTitle());
    Blob fileBlob = (Blob) file.getPropertyValue("file:content");
    assertEquals("File new name.odt", fileBlob.getFilename());
    fileItem = (FileItem) fsItem;
    assertEquals(
        "nxfile/test/" + file.getId() + "/blobholder:0/File%20new%20name.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(fileBlob.getDigest(), fileItem.getDigest());

    // File rename with title == filename
    // => should rename filename and title
    blob = new StringBlob("File for a doc with title == filename.");
    blob.setFilename("Title-filename equality.odt");
    blob.setMimeType("application/vnd.oasis.opendocument.text");
    fileItem = fileSystemItemManagerService.createFile(newFolderItem.getId(), blob, principal);
    // Note that the PathSegmentService truncates doc title at 24 characters
    newFile =
        session.getDocument(
            new PathRef("/syncRoot1/aFolder/A new folder/Title-filename equality."));
    assertEquals("Title-filename equality.odt", newFile.getTitle());
    assertEquals(
        "Title-filename equality.odt",
        ((Blob) newFile.getPropertyValue("file:content")).getFilename());
    fileItem =
        (FileItem)
            fileSystemItemManagerService.rename(
                DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + newFile.getId(),
                "Renamed title-filename equality.odt",
                principal);
    assertEquals("Renamed title-filename equality.odt", fileItem.getName());
    newFile = session.getDocument(newFile.getRef());
    assertEquals("Renamed title-filename equality.odt", newFile.getTitle());
    newFileBlob = (Blob) newFile.getPropertyValue("file:content");
    assertEquals("Renamed title-filename equality.odt", newFileBlob.getFilename());
    assertEquals(
        "nxfile/test/" + newFile.getId() + "/blobholder:0/Renamed%20title-filename%20equality.odt",
        fileItem.getDownloadURL());
    assertEquals("MD5", fileItem.getDigestAlgorithm());
    assertEquals(newFileBlob.getDigest(), fileItem.getDigest());

    // ------------------------------------------------------
    // Check #move
    // ------------------------------------------------------
    // 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();
    try {
      fileSystemItemManagerService.move(srcFsItemId, destFsItemId, principal);
      fail("Move to a non folder item should fail.");
    } catch (NuxeoException e) {
      assertEquals(
          String.format(
              "Cannot move a file system item to file system item with id %s because it is not a folder.",
              DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + file.getId()),
          e.getMessage());
    }

    // Move to a FolderItem
    destFsItemId = DEFAULT_FILE_SYSTEM_ITEM_ID_PREFIX + subFolder.getId();
    FileSystemItem movedFsItem =
        fileSystemItemManagerService.move(srcFsItemId, destFsItemId, principal);
    assertEquals(srcFsItemId, movedFsItem.getId());
    assertEquals(destFsItemId, movedFsItem.getParentId());
    assertEquals("aNote.txt", movedFsItem.getName());
    note = session.getDocument(note.getRef());
    assertEquals("/syncRoot1/aFolder/aSubFolder/aNote", note.getPathAsString());
    assertEquals("aNote", note.getTitle());
  }
Beispiel #10
0
 @OperationMethod
 public Blob run(DocumentModel doc) throws Exception {
   return Blobs.createBlob(doc.getTitle());
 }