@After
 public void tearDown() throws Exception {
   if (accessApproval != null && accessApproval.getId() != null) {
     accessApprovalDAO.delete(accessApproval.getId().toString());
   }
   if (accessApproval2 != null && accessApproval2.getId() != null) {
     accessApprovalDAO.delete(accessApproval2.getId().toString());
   }
   if (accessRequirement != null && accessRequirement.getId() != null) {
     accessRequirementDAO.delete(accessRequirement.getId().toString());
   }
   if (accessRequirement2 != null && accessRequirement2.getId() != null) {
     accessRequirementDAO.delete(accessRequirement2.getId().toString());
   }
   if (node != null && nodeDAO != null) {
     nodeDAO.delete(node.getId());
     node = null;
   }
   if (node2 != null && nodeDAO != null) {
     nodeDAO.delete(node2.getId());
     node2 = null;
   }
   if (evaluation != null && evaluationDAO != null) {
     evaluationDAO.delete(evaluation.getId());
     evaluation = null;
   }
   individualGroup = userGroupDAO.findGroup(TEST_USER_NAME, true);
   if (individualGroup != null) {
     userGroupDAO.delete(individualGroup.getId());
   }
   individualGroup2 = userGroupDAO.findGroup(TEST_USER_NAME_2, true);
   if (individualGroup2 != null) {
     userGroupDAO.delete(individualGroup2.getId());
   }
 }
 public static TermsOfUseAccessRequirement newAccessRequirement(UserGroup principal, Node node)
     throws DatastoreException {
   TermsOfUseAccessRequirement accessRequirement = new TermsOfUseAccessRequirement();
   accessRequirement.setCreatedBy(principal.getId());
   accessRequirement.setCreatedOn(new Date());
   accessRequirement.setModifiedBy(principal.getId());
   accessRequirement.setModifiedOn(new Date());
   accessRequirement.setEtag("10");
   accessRequirement.setAccessType(ACCESS_TYPE.DOWNLOAD);
   accessRequirement.setEntityIds(
       Arrays.asList(
           new String[] {
             node.getId(), node.getId()
           })); // test that repeated IDs doesn't break anything
   accessRequirement.setEntityType("com.sagebionetworks.repo.model.TermsOfUseAccessRequirements");
   return accessRequirement;
 }
 @Before
 public void setUp() throws Exception {
   individualGroup = userGroupDAO.findGroup(TEST_USER_NAME, true);
   if (individualGroup == null) {
     individualGroup = new UserGroup();
     individualGroup.setName(TEST_USER_NAME);
     individualGroup.setIsIndividual(true);
     individualGroup.setCreationDate(new Date());
     individualGroup.setId(userGroupDAO.create(individualGroup));
   }
   if (node == null) {
     node = NodeTestUtils.createNew("foo", Long.parseLong(individualGroup.getId()));
     node.setId(nodeDAO.createNew(node));
   }
   ;
   if (node2 == null) {
     node2 = NodeTestUtils.createNew("bar", Long.parseLong(individualGroup.getId()));
     node2.setId(nodeDAO.createNew(node2));
   }
   ;
 }
  @Before
  public void setUp() throws DatastoreException, InvalidModelException, NotFoundException {
    // create a node
    Node toCreate = NodeTestUtils.createNew(name, userId);
    toCreate.setVersionComment("This is the first version of the first node ever!");
    toCreate.setVersionLabel("0.0.1");
    nodeId = nodeDAO.createNew(toCreate).substring(3); // trim "syn" from node ID

    // Initialize a new Evaluation
    EvaluationDBO evaluation = new EvaluationDBO();
    evaluation.setId(evalId);
    evaluation.seteTag("etag");
    evaluation.setName("name");
    evaluation.setOwnerId(userId);
    evaluation.setContentSource(KeyFactory.ROOT_ID);
    evaluation.setCreatedOn(System.currentTimeMillis());
    evaluation.setStatusEnum(EvaluationStatus.PLANNED);
    evalId = dboBasicDao.createNew(evaluation).getId();

    // Initialize a new Participant
    ParticipantDBO participant = new ParticipantDBO();
    participant.setUserId(userId);
    participant.setEvalId(evalId);
    participant.setCreatedOn(System.currentTimeMillis());
    participant.setId(idGenerator.generateNewId(TYPE.PARTICIPANT_ID));
    dboBasicDao.createNew(participant);

    // Initialize a new Submission
    SubmissionDBO submission = new SubmissionDBO();
    submission.setId(submissionId);
    submission.setName(name);
    submission.setEntityId(Long.parseLong(nodeId));
    submission.setVersionNumber(1L);
    submission.setUserId(userId);
    submission.setEvalId(evalId);
    submission.setCreatedOn(System.currentTimeMillis());
    dboBasicDao.createNew(submission);
  }
  @Test
  public void testCRUD() throws Exception {
    // Create a new object
    accessRequirement = newAccessRequirement(individualGroup, node);
    // PLFM-1477, we have to check that retrieval works when there is another access requirement
    accessRequirement2 = newAccessRequirement(individualGroup, node2);

    long initialCount = accessRequirementDAO.getCount();

    // Create it
    TermsOfUseAccessRequirement accessRequirementCopy =
        accessRequirementDAO.create(accessRequirement);
    accessRequirement = accessRequirementCopy;
    assertNotNull(accessRequirementCopy.getId());

    assertEquals(1 + initialCount, accessRequirementDAO.getCount());

    // Fetch it
    // PLFM-1477, we have to check that retrieval works when there is another access requirement
    accessRequirement2 = accessRequirementDAO.create(accessRequirement2);
    AccessRequirement clone = accessRequirementDAO.get(accessRequirement.getId().toString());
    assertNotNull(clone);
    assertEquals(accessRequirement, clone);

    // Get by Node Id
    Collection<AccessRequirement> ars = accessRequirementDAO.getForNode(node.getId());
    assertEquals(1, ars.size());
    assertEquals(accessRequirement, ars.iterator().next());

    // update it
    clone = ars.iterator().next();
    clone.setAccessType(ACCESS_TYPE.READ);
    AccessRequirement updatedAR = accessRequirementDAO.update(clone);
    assertEquals(clone.getAccessType(), updatedAR.getAccessType());

    assertTrue(
        "etags should be different after an update", !clone.getEtag().equals(updatedAR.getEtag()));

    try {
      ((TermsOfUseAccessRequirement) clone).setTermsOfUse("bar");
      accessRequirementDAO.update(clone);
      fail("conflicting update exception not thrown");
    } catch (ConflictingUpdateException e) {
      // We expected this exception
    }

    try {
      // Update from a backup.
      updatedAR = accessRequirementDAO.updateFromBackup(clone);
      assertEquals(clone.getEtag(), updatedAR.getEtag());
    } catch (ConflictingUpdateException e) {
      fail("Update from backup should not generate exception even if the e-tag is different.");
    }

    QueryResults<MigratableObjectData> migrationData =
        accessRequirementDAO.getMigrationObjectData(0, 10000, true);

    List<MigratableObjectData> results = migrationData.getResults();
    assertEquals(1 + 1 + initialCount, results.size()); // "+1" for extra AR added to test PLFM-1477
    assertEquals(migrationData.getTotalNumberOfResults(), results.size());

    boolean foundAr = false;
    for (MigratableObjectData od : results) {
      MigratableObjectDescriptor obj = od.getId();
      assertNotNull(obj.getId());
      assertNotNull(od.getEtag());
      assertEquals(MigratableObjectType.ACCESSREQUIREMENT, obj.getType());
      assertNotNull(od.getDependencies());
      if (obj.getId().equals(clone.getId().toString())) {
        foundAr = true;
        Collection<MigratableObjectDescriptor> deps = od.getDependencies();
        assertTrue(deps.size() > 0); // is dependent on 'node'
        boolean foundNode = false;
        for (MigratableObjectDescriptor d : deps) {
          if (d.getId().equals(node.getId())) {
            foundNode = true;
          }
          assertEquals(MigratableObjectType.ENTITY, d.getType());
        }
        assertTrue("dependencies: " + deps, foundNode);
      }
    }
    assertTrue(foundAr);

    // Delete it
    accessRequirementDAO.delete(accessRequirement.getId().toString());
    accessRequirementDAO.delete(accessRequirement2.getId().toString());

    assertEquals(initialCount, accessRequirementDAO.getCount());
  }
  @Before
  public void setUp() throws Exception {
    individualGroup = userGroupDAO.findGroup(TEST_USER_NAME, true);
    if (individualGroup == null) {
      individualGroup = new UserGroup();
      individualGroup.setName(TEST_USER_NAME);
      individualGroup.setIsIndividual(true);
      individualGroup.setCreationDate(new Date());
      individualGroup.setId(userGroupDAO.create(individualGroup));
    }
    individualGroup2 = userGroupDAO.findGroup(TEST_USER_NAME, true);
    if (individualGroup2 == null) {
      individualGroup2 = new UserGroup();
      individualGroup2.setName(TEST_USER_NAME_2);
      individualGroup2.setIsIndividual(true);
      individualGroup2.setCreationDate(new Date());
      individualGroup2.setId(userGroupDAO.create(individualGroup2));
    }
    if (node == null) {
      node = NodeTestUtils.createNew("foo", Long.parseLong(individualGroup.getId()));
      node.setId(nodeDAO.createNew(node));
    }
    ;
    if (node2 == null) {
      node2 = NodeTestUtils.createNew("bar", Long.parseLong(individualGroup.getId()));
      node2.setId(nodeDAO.createNew(node2));
    }
    ;
    accessRequirement =
        DBOAccessRequirementDAOImplTest.newEntityAccessRequirement(individualGroup, node, "foo");
    accessRequirement = accessRequirementDAO.create(accessRequirement);
    Long id = accessRequirement.getId();
    assertNotNull(id);

    if (evaluation == null) {
      evaluation =
          DBOAccessRequirementDAOImplTest.createNewEvaluation(
              "foo", individualGroup.getId(), idGenerator, node.getId());
      evaluation.setId(evaluationDAO.create(evaluation, Long.parseLong(individualGroup.getId())));
    }
    ;
    accessRequirement2 =
        DBOAccessRequirementDAOImplTest.newMixedAccessRequirement(
            individualGroup, node2, evaluation, "bar");
    accessRequirement2 = accessRequirementDAO.create(accessRequirement2);
    id = accessRequirement2.getId();
    assertNotNull(id);

    if (participateAndDownload == null) {
      participateAndDownload = new ArrayList<ACCESS_TYPE>();
      participateAndDownload.add(ACCESS_TYPE.DOWNLOAD);
      participateAndDownload.add(ACCESS_TYPE.PARTICIPATE);
    }

    if (downloadAccessType == null) {
      downloadAccessType = new ArrayList<ACCESS_TYPE>();
      downloadAccessType.add(ACCESS_TYPE.DOWNLOAD);
    }
    if (updateAccessType == null) {
      updateAccessType = new ArrayList<ACCESS_TYPE>();
      updateAccessType.add(ACCESS_TYPE.UPDATE);
    }
  }
  @Test
  public void testCRUD() throws Exception {
    // first of all, we should see the unmet requirement
    RestrictableObjectDescriptor rod =
        AccessRequirementUtilsTest.createRestrictableObjectDescriptor(node.getId());
    List<Long> unmetARIds =
        accessRequirementDAO.unmetAccessRequirements(
            rod,
            Arrays.asList(new Long[] {Long.parseLong(individualGroup.getId())}),
            downloadAccessType);
    assertEquals(1, unmetARIds.size());
    assertEquals(accessRequirement.getId(), unmetARIds.iterator().next());
    // while we're at it, check the edge cases:
    // same result for ficticious principal ID
    unmetARIds =
        accessRequirementDAO.unmetAccessRequirements(
            rod, Arrays.asList(new Long[] {8888L}), downloadAccessType);
    assertEquals(1, unmetARIds.size());
    assertEquals(accessRequirement.getId(), unmetARIds.iterator().next());
    // no unmet requirements for ficticious node ID
    assertTrue(
        accessRequirementDAO
            .unmetAccessRequirements(
                AccessRequirementUtilsTest.createRestrictableObjectDescriptor("syn7890"),
                Arrays.asList(new Long[] {Long.parseLong(individualGroup.getId())}),
                downloadAccessType)
            .isEmpty());
    // no unmet requirement for other type of access
    assertTrue(
        accessRequirementDAO
            .unmetAccessRequirements(
                rod,
                Arrays.asList(new Long[] {Long.parseLong(individualGroup.getId())}),
                updateAccessType)
            .isEmpty());

    // Create a new object
    accessApproval = newAccessApproval(individualGroup, accessRequirement);

    // Create it
    accessApproval = accessApprovalDAO.create(accessApproval);
    String id = accessApproval.getId().toString();
    assertNotNull(id);

    // no unmet requirement anymore ...
    assertTrue(
        accessRequirementDAO
            .unmetAccessRequirements(
                rod,
                Arrays.asList(new Long[] {Long.parseLong(individualGroup.getId())}),
                downloadAccessType)
            .isEmpty());
    // ... but for a different (ficticious) user, the requirement isn't met...
    unmetARIds =
        accessRequirementDAO.unmetAccessRequirements(
            rod, Arrays.asList(new Long[] {8888L}), downloadAccessType);
    assertEquals(1, unmetARIds.size());
    assertEquals(accessRequirement.getId(), unmetARIds.iterator().next());
    // ... and it's still unmet for the second node
    RestrictableObjectDescriptor rod2 =
        AccessRequirementUtilsTest.createRestrictableObjectDescriptor(node2.getId());
    unmetARIds =
        accessRequirementDAO.unmetAccessRequirements(
            rod2,
            Arrays.asList(new Long[] {Long.parseLong(individualGroup.getId())}),
            participateAndDownload);
    assertEquals(1, unmetARIds.size());
    assertEquals(accessRequirement2.getId(), unmetARIds.iterator().next());

    // Fetch it
    AccessApproval clone = accessApprovalDAO.get(id);
    assertNotNull(clone);
    assertEquals(accessApproval, clone);

    // Get by Node Id
    Collection<AccessApproval> ars =
        accessApprovalDAO.getForAccessRequirementsAndPrincipals(
            Arrays.asList(new String[] {accessRequirement.getId().toString()}),
            Arrays.asList(new String[] {individualGroup.getId().toString()}));
    assertEquals(1, ars.size());
    assertEquals(accessApproval, ars.iterator().next());

    // update it
    clone = ars.iterator().next();
    AccessApproval updatedAA = accessApprovalDAO.update(clone);
    assertEquals(
        ((TermsOfUseAccessApproval) clone).getEntityType(),
        ((TermsOfUseAccessApproval) updatedAA).getEntityType());
    assertTrue(
        "etags should be different after an update", !clone.getEtag().equals(updatedAA.getEtag()));

    try {
      accessApprovalDAO.update(clone);
      fail("conflicting update exception not thrown");
    } catch (ConflictingUpdateException e) {
      // We expected this exception
    }

    try {
      // Update from a backup.
      updatedAA = accessApprovalDAO.updateFromBackup(clone);
      assertEquals(clone.getEtag(), updatedAA.getEtag());
    } catch (ConflictingUpdateException e) {
      fail("Update from backup should not generate exception even if the e-tag is different.");
    }

    // Delete it
    accessApprovalDAO.delete(id);
  }