Beispiel #1
0
  @Test
  public void shouldUnIndexSubTree() throws Exception {
    buildAndIndexTree();

    DocumentRef ref = new PathRef("/folder0/folder1/folder2");
    Assert.assertTrue(session.exists(ref));

    startTransaction();
    session.removeDocument(ref);
    TransactionHelper.commitOrRollbackTransaction();
    waitForCompletion();
    assertNumberOfCommandProcessed(1);

    startTransaction();
    SearchResponse searchResponse =
        esa.getClient()
            .prepareSearch(IDX_NAME)
            .setTypes(TYPE_NAME)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setFrom(0)
            .setSize(60)
            .execute()
            .actionGet();
    Assert.assertEquals(2, searchResponse.getHits().getTotalHits());
  }
  @Override
  public void initTree(
      String sid,
      CoreSession coreSession,
      Map<String, String> parameters,
      PublishedDocumentFactory factory,
      String configName,
      String title) {
    super.initTree(sid, coreSession, parameters, factory, configName, title);

    DocumentRef ref = new PathRef(rootPath);
    boolean exists = coreSession.exists(ref);
    if (!exists) {
      log.debug(
          "Root section "
              + rootPath
              + " doesn't exist. Check "
              + "publicationTreeConfig with name "
              + configName);
    }
    if (exists && coreSession.hasPermission(ref, SecurityConstants.READ)) {
      treeRoot = coreSession.getDocument(new PathRef(rootPath));
      rootNode = new CoreFolderPublicationNode(treeRoot, getConfigName(), sid, factory);
    } else {
      rootNode =
          new VirtualCoreFolderPublicationNode(
              coreSession.getSessionId(), rootPath, getConfigName(), sid, factory);
      sessionId = coreSession.getSessionId();
    }
  }
  public DocumentModel getDocumentFor(String mainTabId, DocumentModel defaultDocument) {
    DocumentModel doc = documentsByMainTabs.get(mainTabId);
    if (doc == null
        || !documentManager.exists(doc.getRef())
        || !documentManager.hasPermission(doc.getRef(), SecurityConstants.READ)) {
      documentsByMainTabs.put(mainTabId, defaultDocument);
      doc = null;
    }

    if (doc != null && !documentManager.exists(new PathRef(doc.getPathAsString()))) {
      // path has changed, refresh the document to have a correct URL
      doc = documentManager.getDocument(doc.getRef());
      documentsByMainTabs.put(mainTabId, doc);
    }

    return doc != null ? doc : defaultDocument;
  }
Beispiel #4
0
  @Test
  public void shouldReindexSubTreeInTrash() throws Exception {
    buildAndIndexTree();
    startTransaction();
    DocumentRef ref = new PathRef("/folder0/folder1/folder2");
    Assert.assertTrue(session.exists(ref));
    session.followTransition(ref, "delete");

    TransactionHelper.commitOrRollbackTransaction();
    // let the bulkLifeCycleChangeListener do its work
    waitForCompletion();
    assertNumberOfCommandProcessed(8);

    startTransaction();
    DocumentModelList docs =
        ess.query(
            new NxQueryBuilder(session)
                .nxql("select * from Document where ecm:currentLifeCycleState != 'deleted'"));
    // for (DocumentModel doc : docs) {
    // System.out.println(doc.getPathAsString());
    // }
    Assert.assertEquals(2, docs.totalSize());
  }
  @Override
  public void execute(CoreSession session) {
    try {
      DamService damService = Framework.getLocalService(DamService.class);
      AssetLibrary assetLibrary = damService.getAssetLibrary();
      if (assetLibrary != null) {
        DocumentRef docRef = new PathRef(assetLibrary.getPath());
        if (!session.exists(docRef)) {
          Path path = new Path(assetLibrary.getPath());
          String parentPath = path.removeLastSegments(1).toString();
          String name = path.lastSegment();

          DocumentModel doc =
              session.createDocumentModel(parentPath, name, Constants.IMPORT_ROOT_TYPE);
          doc.setPropertyValue(DC_TITLE, assetLibrary.getTitle());
          doc.setPropertyValue(DC_DESCRIPTION, assetLibrary.getDescription());
          session.createDocument(doc);
        }
      }
    } catch (ClientException e) {
      throw new ClientRuntimeException(e);
    }
  }
  @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));
  }
Beispiel #7
0
  @SuppressWarnings({"unchecked", "boxing"})
  public static AdditionalDocumentAuditParams getAuditParamsForUUID(
      String uuid, CoreSession session) {

    AdditionalDocumentAuditParams result = null;
    IdRef ref = new IdRef(uuid);
    if (session.exists(ref)) {
      DocumentModel doc = session.getDocument(ref);

      String targetUUID = null;

      if (doc.isProxy() || doc.isVersion()) {
        SourceDocumentResolver resolver = new SourceDocumentResolver(session, doc);
        resolver.runUnrestricted();
        if (resolver.sourceDocument != null) {
          targetUUID = resolver.sourceDocument.getId();

          // now get from Audit Logs the creation date of
          // the version / proxy
          AuditReader reader = Framework.getLocalService(AuditReader.class);
          FilterMapEntry filter = new FilterMapEntry();
          filter.setColumnName("eventId");
          filter.setOperator("=");
          filter.setQueryParameterName("eventId");
          filter.setObject(DocumentEventTypes.DOCUMENT_CREATED);
          Map<String, FilterMapEntry> filters = new HashMap<String, FilterMapEntry>();
          filters.put("eventId", filter);
          List<LogEntry> entries = reader.getLogEntriesFor(uuid, filters, false);

          if (entries != null && entries.size() > 0) {
            result = new AdditionalDocumentAuditParams();
            result.maxDate = entries.get(0).getEventDate();
            result.targetUUID = targetUUID;
            result.eventId = entries.get(0).getId();
          } else {
            // we have no entry in audit log to get the maxDate
            // fallback to repository timestamp
            // this code is here only for compatibility
            // so that it works before version events were added to
            // the audit log
            if (doc.getPropertyValue("dc:modified") != null) {
              result = new AdditionalDocumentAuditParams();
              Calendar estimatedDate = ((Calendar) doc.getPropertyValue("dc:modified"));

              // We can not directly use the repo timestamp
              // because Audit and VCS can be in separated DB
              // => try to find the matching TS in Audit
              StringBuilder queryString = new StringBuilder();
              queryString.append("from LogEntry log where log.docUUID in (");
              queryString.append("'" + targetUUID + "'");
              if (doc.isVersion()) {
                DocumentModelList proxies = session.getProxies(doc.getRef(), null);
                for (DocumentModel proxy : proxies) {
                  queryString.append(",'" + proxy.getId() + "'");
                }
              }
              queryString.append(",'" + doc.getId() + "'");
              queryString.append(") AND log.eventId IN (");
              queryString.append("'" + DocumentEventTypes.DOCUMENT_CREATED + "'");
              queryString.append(",'" + DocumentEventTypes.DOCUMENT_CHECKEDIN + "'");
              queryString.append(") AND log.eventDate >= :minDate ");
              queryString.append(" order by log.eventId asc");

              estimatedDate.add(Calendar.MILLISECOND, -500);
              Map<String, Object> params = new HashMap<String, Object>();
              params.put("minDate", estimatedDate.getTime());

              List<LogEntry> dateEntries =
                  (List<LogEntry>) reader.nativeQuery(queryString.toString(), params, 0, 20);
              if (dateEntries.size() > 0) {
                result.targetUUID = targetUUID;
                Calendar maxDate = new GregorianCalendar();
                maxDate.setTime(dateEntries.get(0).getEventDate());
                maxDate.add(Calendar.MILLISECOND, -500);
                result.maxDate = maxDate.getTime();
              } else {
                // no other choice : use the VCS TS
                // results may be truncated in some DB config
                result.targetUUID = targetUUID;
                result.maxDate = ((Calendar) doc.getPropertyValue("dc:modified")).getTime();
              }
            }
          }
        }
      }
    }
    return result;
  }
Beispiel #8
0
  @Test
  public void shouldIndexMovedSubTree() throws Exception {
    buildAndIndexTree();
    startTransaction();
    DocumentRef ref = new PathRef("/folder0/folder1/folder2");
    Assert.assertTrue(session.exists(ref));
    DocumentModel doc = session.getDocument(ref);

    // move in the same folder : rename
    session.move(ref, doc.getParentRef(), "folderA");

    TransactionHelper.commitOrRollbackTransaction();
    waitForCompletion();
    if (syncMode) {
      // in sync we split recursive update into 2 commands:
      // 1 sync non recurse + 1 async recursive
      assertNumberOfCommandProcessed(9);
    } else {
      assertNumberOfCommandProcessed(8);
    }

    startTransaction();
    SearchResponse searchResponse =
        esa.getClient()
            .prepareSearch(IDX_NAME)
            .setTypes(TYPE_NAME)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setFrom(0)
            .setSize(60)
            .execute()
            .actionGet();
    Assert.assertEquals(10, searchResponse.getHits().getTotalHits());

    // check sub tree search
    searchResponse =
        esa.getClient()
            .prepareSearch(IDX_NAME)
            .setTypes(TYPE_NAME)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.prefixQuery("ecm:path", "/folder0/folder1/folder2"))
            .execute()
            .actionGet();
    Assert.assertEquals(0, searchResponse.getHits().getTotalHits());

    searchResponse =
        esa.getClient()
            .prepareSearch(IDX_NAME)
            .setTypes(TYPE_NAME)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.prefixQuery("ecm:path", "/folder0/folder1/folderA"))
            .execute()
            .actionGet();
    Assert.assertEquals(8, searchResponse.getHits().getTotalHits());

    searchResponse =
        esa.getClient()
            .prepareSearch(IDX_NAME)
            .setTypes(TYPE_NAME)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(QueryBuilders.prefixQuery("ecm:path", "/folder0/folder1"))
            .execute()
            .actionGet();
    Assert.assertEquals(9, searchResponse.getHits().getTotalHits());
  }
  protected void createNewDocument(Element el, DocConfigDescriptor conf) {
    DocumentModel doc = session.createDocumentModel(conf.getDocType());

    String path = resolvePath(el, conf.getParent());
    Object nameOb = resolveName(el, conf.getName());
    String name = null;
    if (nameOb == null) {
      if (log.isDebugEnabled()) {
        log.debug(String.format(MSG_NO_ELEMENT_FOUND, conf.getName(), el.getUniquePath()));
      }
      int idx = 1;
      for (int i = 0; i < docsStack.size(); i++) {
        if (docsStack.get(i).getType().equals(conf.getDocType())) {
          idx++;
        }
      }
      name = conf.getDocType() + "-" + idx;
    } else {
      name = nameOb.toString();
    }
    doc.setPathInfo(path, name);

    if (log.isDebugEnabled()) {
      if (conf.getUpdate()) {
        log.debug(String.format(MSG_UPDATE, path, name, el.getUniquePath(), conf.toString()));
      } else {
        log.debug(String.format(MSG_CREATION, path, name, el.getUniquePath(), conf.toString()));
      }
    }

    try {
      if (conf.getUpdate() && session.exists(doc.getRef())) {
        DocumentModel existingDoc = session.getDocument(doc.getRef());

        // get attributes, if attribute needs to be overwritten, empty in the document
        for (Object e : el.elements()) {
          List<AttributeConfigDescriptor> configs = getAttributConfigs((Element) e);
          if (configs != null) {
            if (!deletedAttributes.containsKey(existingDoc.getId())) {
              deletedAttributes.put(existingDoc.getId(), new ArrayList<String>());
            }
            for (AttributeConfigDescriptor config : configs) {
              String targetDocProperty = config.getTargetDocProperty();
              // check deletedAttributes for attribute which should be overwritten
              // if it is there, don't empty it a second time
              if (config.overwrite
                  && !deletedAttributes.get(existingDoc.getId()).contains(targetDocProperty)) {
                deletedAttributes.get(existingDoc.getId()).add(targetDocProperty);
                existingDoc.setPropertyValue(targetDocProperty, new ArrayList<>());
              }
            }
          }
        }
        doc = existingDoc;
      } else {
        doc = session.createDocument(doc);
      }
    } catch (NuxeoException e) {
      e.addInfo(String.format(MSG_CREATION, path, name, el.getUniquePath(), conf.toString()));
      throw e;
    }
    pushInStack(doc);
    elToDoc.put(el, doc);
  }