/** @throws java.lang.Exception */
  @Before
  public void setUp() throws Exception {
    testHelper.setUp();
    testHelper.setTestUser(TEST_USER1);

    project = new Project();
    project.setName("proj");
    project = testHelper.createEntity(project, null);

    dataset = new Study();
    dataset.setName("study");
    dataset.setParentId(project.getId());
    dataset = testHelper.createEntity(dataset, null);

    // Add a public read ACL to the project object
    AccessControlList projectAcl = testHelper.getEntityACL(project);
    ResourceAccess ac = new ResourceAccess();
    UserGroup authenticatedUsers =
        userGroupDAO.findGroup(
            AuthorizationConstants.DEFAULT_GROUPS.AUTHENTICATED_USERS.name(), false);
    assertNotNull(authenticatedUsers);
    ac.setPrincipalId(Long.parseLong(authenticatedUsers.getId()));
    ac.setAccessType(new HashSet<ACCESS_TYPE>());
    ac.getAccessType().add(ACCESS_TYPE.READ);
    projectAcl.getResourceAccess().add(ac);
    projectAcl = testHelper.updateEntityAcl(project, projectAcl);

    testUser = userGroupDAO.findGroup(TEST_USER1, true);
  }
  @Test
  public void testcreateS3AttachmentToken()
      throws JSONObjectAdapterException, ServletException, IOException, DatastoreException {
    S3AttachmentToken startToken = new S3AttachmentToken();
    startToken.setFileName("someImage.jpg");
    startToken.setMd5(TEST_MD5);

    String fileName = "images/notAnImage.txt";
    URL toUpUrl = S3TokenControllerTest.class.getClassLoader().getResource(fileName);
    assertNotNull("Failed to find: " + fileName + " on the classpath", toUpUrl);
    File toUpload = new File(toUpUrl.getFile());
    // Create the token
    S3AttachmentToken resultToken =
        testHelper.createS3AttachmentToken(
            TestUserDAO.TEST_USER_NAME,
            ServiceConstants.AttachmentType.ENTITY,
            project.getId(),
            startToken);
    System.out.println(resultToken);
    assertNotNull(resultToken);
    assertNotNull(resultToken.getTokenId());
    assertNotNull(resultToken.getPresignedUrl());

    // Upload it
    String path =
        S3TokenManagerImpl.createAttachmentPathNoSlash(project.getId(), resultToken.getTokenId());
    s3Utility.uploadToS3(toUpload, path);

    // Make sure we can get a signed download URL for this attachment.
    long now = System.currentTimeMillis();
    long oneMinuteFromNow = now + (60 * 1000);
    PresignedUrl url =
        testHelper.getAttachmentUrl(
            TestUserDAO.TEST_USER_NAME, project.getId(), resultToken.getTokenId());
    System.out.println(url);
    assertNotNull(url);
    assertNotNull(url.getPresignedUrl());
    URL urlReal = new URL(url.getPresignedUrl());
    // Check that it expires quickly.
    String[] split = urlReal.getQuery().split("&");
    assertTrue(split.length > 1);
    String[] expiresSplit = split[0].split("=");
    assertEquals("Expires", expiresSplit[0]);
    // It should expire within a minute max
    Long expirsInt = Long.parseLong(expiresSplit[1]);
    long expiresMil = expirsInt.longValue() * 1000l;
    System.out.println("Now: " + new Date(now));
    System.out.println("Expires: " + new Date(expiresMil));
    assertTrue("This URL should expire in under a minute!", expiresMil < oneMinuteFromNow);
    assertTrue("This URL should expire after now!", now <= expiresMil);

    // Delete the file
    s3Utility.deleteFromS3(path);
  }
  /** @throws Exception */
  @Test
  public void testCreateS3TokenRelativePath() throws Exception {
    Code code = new Code();
    code.setParentId(project.getId());
    code = testHelper.createEntity(code, null);

    // a relative path to a file
    String initialPath = "foo.java";
    S3Token token = new S3Token();
    token.setPath(initialPath);
    token.setMd5(TEST_MD5);

    token = testHelper.createObject(code.getS3Token(), token);

    assertEquals(StackConfiguration.getS3Bucket(), token.getBucket());
    assertTrue(
        token
            .getPath()
            .matches("^/" + KeyFactory.stringToKey(code.getId()) + "/\\d+/" + initialPath + "$"));
    assertEquals(TEST_MD5, token.getMd5());
    assertEquals("text/plain", token.getContentType());
    assertNotNull(token.getSecretAccessKey());
    assertNotNull(token.getAccessKeyId());
    assertNotNull(token.getSessionToken());
    assertTrue(token.getPresignedUrl().matches("^http.*" + initialPath + ".*"));
  }
  @Test(expected = IllegalArgumentException.class)
  public void testProjectWithDatasetParent()
      throws InvalidModelException, NotFoundException, DatastoreException, UnauthorizedException {
    String parentId = "123";
    // This is our parent header
    EntityHeader parentHeader = new EntityHeader();
    parentHeader.setId(parentId);
    parentHeader.setName("name");
    parentHeader.setType(EntityType.dataset.getEntityType());
    List<EntityHeader> path = new ArrayList<EntityHeader>();
    path.add(parentHeader);

    Project project = new Project();
    project.setParentId(parentId);
    // This should not be valid
    allTypesValidator.validateEntity(project, new EntityEvent(EventType.CREATE, path, null));
  }
  @Test
  public void testPLFM_1288() throws Exception {
    Project p = new Project();
    p.setName("Create without entity type");
    p.setEntityType(p.getClass().getName());
    p = (Project) entityServletHelper.createEntity(p, TEST_USER1);
    toDelete.add(p.getId());

    Study one = new Study();
    one.setName("one");
    one.setParentId(p.getId());
    one.setEntityType(Study.class.getName());
    one = (Study) entityServletHelper.createEntity(one, TEST_USER1);
    // Now try to re-use the name
    Code two = new Code();
    two.setName("code");
    two.setParentId(one.getId());
    two.setEntityType(Code.class.getName());
    try {
      two = (Code) entityServletHelper.createEntity(two, TEST_USER1);
      fail("Code cannot have a parent of type Study");
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
      assertTrue(e.getMessage().indexOf(Code.class.getName()) > 0);
      assertTrue(e.getMessage().indexOf(Study.class.getName()) > 0);
    }
  }
 @Test
 public void testGetUserEntityPermissions()
     throws JSONObjectAdapterException, ServletException, IOException, NotFoundException,
         DatastoreException {
   Project p = new Project();
   p.setName("UserEntityPermissions");
   p.setEntityType(p.getClass().getName());
   Project clone = (Project) entityServletHelper.createEntity(p, TEST_USER1);
   String id = clone.getId();
   toDelete.add(id);
   UserEntityPermissions uep = entityServletHelper.getUserEntityPermissions(id, TEST_USER1);
   assertNotNull(uep);
   assertTrue(uep.getCanEdit());
 }
  @Test(expected = NameConflictException.class)
  public void testPLFM_449NameConflict() throws Exception {
    Project p = new Project();
    p.setName("Create without entity type");
    p.setEntityType(p.getClass().getName());
    p = (Project) entityServletHelper.createEntity(p, TEST_USER1);
    toDelete.add(p.getId());

    Study one = new Study();
    one.setName("one");
    one.setParentId(p.getId());
    one.setEntityType(Study.class.getName());
    one = (Study) entityServletHelper.createEntity(one, TEST_USER1);
    // Now try to re-use the name
    Study two = new Study();
    two.setName("one");
    two.setParentId(p.getId());
    two.setEntityType(Study.class.getName());
    two = (Study) entityServletHelper.createEntity(two, TEST_USER1);
  }
 @Test
 public void testEntityPath()
     throws JSONObjectAdapterException, ServletException, IOException, NotFoundException,
         DatastoreException {
   Project p = new Project();
   p.setName("EntityPath");
   p.setEntityType(p.getClass().getName());
   Project clone = (Project) entityServletHelper.createEntity(p, TEST_USER1);
   String id = clone.getId();
   toDelete.add(id);
   EntityPath path = entityServletHelper.getEntityPath(id, TEST_USER1);
   assertNotNull(path);
   assertNotNull(path.getPath());
   assertEquals(2, path.getPath().size());
   EntityHeader header = path.getPath().get(1);
   assertNotNull(header);
   assertEquals(id, header.getId());
 }
  @Test
  public void testEntityTypeBatch() throws Exception {
    List<String> ids = new ArrayList<String>();
    for (int i = 0; i < 12; i++) {
      Project p = new Project();
      p.setName("EntityTypeBatchItem" + i);
      p.setEntityType(p.getClass().getName());
      Project clone = (Project) entityServletHelper.createEntity(p, TEST_USER1);
      String id = clone.getId();
      toDelete.add(id);
      ids.add(id);
    }

    BatchResults<EntityHeader> results = entityServletHelper.getEntityTypeBatch(ids, TEST_USER1);
    assertNotNull(results);
    assertEquals(12, results.getTotalNumberOfResults());
    List<String> outputIds = new ArrayList<String>();
    for (EntityHeader header : results.getResults()) {
      outputIds.add(header.getId());
    }
    assertEquals(ids.size(), outputIds.size());
    assertTrue(ids.containsAll(outputIds));
  }
 @Test
 public void testAnnotationsCRUD() throws Exception {
   Project p = new Project();
   p.setName("AnnotCrud");
   p.setEntityType(p.getClass().getName());
   Project clone = (Project) entityServletHelper.createEntity(p, TEST_USER1);
   String id = clone.getId();
   toDelete.add(id);
   // Get the annotaions for this entity
   Annotations annos = entityServletHelper.getEntityAnnotaions(id, TEST_USER1);
   assertNotNull(annos);
   // Change the values
   annos.addAnnotation("doubleAnno", new Double(45.0001));
   annos.addAnnotation("string", "A string");
   // Updte them
   Annotations annosClone = entityServletHelper.updateAnnotations(annos, TEST_USER1);
   assertNotNull(annosClone);
   assertEquals(id, annosClone.getId());
   assertFalse(annos.getEtag().equals(annosClone.getEtag()));
   String value = (String) annosClone.getSingleValue("string");
   assertEquals("A string", value);
   assertEquals(new Double(45.0001), annosClone.getSingleValue("doubleAnno"));
 }
 @Test
 public void testCRUDEntity() throws Exception {
   Project p = new Project();
   p.setName("Create without entity type");
   p.setEntityType(p.getClass().getName());
   Project clone = (Project) entityServletHelper.createEntity(p, TEST_USER1);
   String id = clone.getId();
   toDelete.add(id);
   assertEquals(p.getName(), clone.getName());
   // Now get the entity with the ID
   Project clone2 = (Project) entityServletHelper.getEntity(id, TEST_USER1);
   assertEquals(clone, clone2);
   // Make sure we can update it
   clone2.setName("My new name");
   Project clone3 = (Project) entityServletHelper.updateEntity(clone2, TEST_USER1);
   assertNotNull(clone3);
   assertEquals(clone2.getName(), clone3.getName());
   // Should not match the original
   assertFalse(p.getName().equals(clone3.getName()));
   // the Etag should have changed
   assertFalse(clone2.getEtag().equals(clone3.getEtag()));
   // Now delete it
   entityServletHelper.deleteEntity(id, TEST_USER1);
   // it should not be found now
   try {
     entityServletHelper.getEntity(id, TEST_USER1);
     fail("Delete failed");
   } catch (NotFoundException e) {
     // expected
   }
 }