/**
   * Add ETag and Last-Modified cache control headers to the response
   *
   * @param servletResponse the servlet response
   * @param resource the fedora resource
   * @param session the session
   */
  protected static void addCacheControlHeaders(
      final HttpServletResponse servletResponse,
      final FedoraResource resource,
      final Session session) {

    final String txId = TransactionServiceImpl.getCurrentTransactionId(session);
    if (txId != null) {
      // Do not add caching headers if in a transaction
      return;
    }

    final FedoraResource mutableResource =
        resource instanceof NonRdfSourceDescription
            ? ((NonRdfSourceDescription) resource).getDescribedResource()
            : resource;
    final EntityTag etag = new EntityTag(mutableResource.getEtagValue());
    final Date date = mutableResource.getLastModifiedDate();

    if (!etag.getValue().isEmpty()) {
      servletResponse.addHeader("ETag", etag.toString());
    }

    if (date != null) {
      servletResponse.addDateHeader("Last-Modified", date.getTime());
    }
  }
 @Before
 public void setUp() throws Exception {
   initMocks(this);
   when(mockResource.getPath()).thenReturn(testPath);
   when(mockResource.getNode()).thenReturn(mockNode);
   when(mockNode.getSession()).thenReturn(mockSession);
 }
  @Test
  public void testChildren() throws RepositoryException {
    when(mockRes1.getPath()).thenReturn(RDF_PATH + "/res1");
    when(mockRes2.getPath()).thenReturn(RDF_PATH + "/res2");
    when(mockRes3.getPath()).thenReturn(RDF_PATH + "/res3");
    when(mockResourceNode.hasNodes()).thenReturn(true);
    final Stream<FedoraResource> first = of(mockRes1, mockRes2, mockRes3);
    final Stream<FedoraResource> second = of(mockRes1, mockRes2, mockRes3);
    when(mockResource.getChildren()).thenReturn(first).thenReturn(second);

    try (final ChildrenRdfContext context = new ChildrenRdfContext(mockResource, idTranslator)) {
      final Model results = context.collect(toModel());
      final Resource subject = idTranslator.reverse().convert(mockResource);

      final StmtIterator stmts =
          results.listStatements(subject, RdfLexicon.HAS_CHILD_COUNT, (RDFNode) null);

      assertTrue("There should have been a statement!", stmts.hasNext());
      final Statement stmt = stmts.nextStatement();
      assertTrue("Object should be a literal! " + stmt.getObject(), stmt.getObject().isLiteral());
      assertEquals(3, stmt.getInt());

      assertFalse("There should not have been a second statement!", stmts.hasNext());
    }
  }
  @Override
  public FedoraResource getVersionedAncestor() {

    try {
      if (!isFrozenResource()) {
        return null;
      }

      Node versionableFrozenNode = getNode();
      FedoraResource unfrozenResource = getUnfrozenResource();

      // traverse the frozen tree looking for a node whose unfrozen equivalent is versioned
      while (!unfrozenResource.isVersioned()) {

        if (versionableFrozenNode.getDepth() == 0) {
          return null;
        }

        // node in the frozen tree
        versionableFrozenNode = versionableFrozenNode.getParent();

        // unfrozen equivalent
        unfrozenResource = new FedoraResourceImpl(versionableFrozenNode).getUnfrozenResource();
      }

      return new FedoraResourceImpl(versionableFrozenNode);
    } catch (final RepositoryException e) {
      throw new RepositoryRuntimeException(e);
    }
  }
  @Before
  public void setUp() throws RepositoryException {
    // Mock RDF Source
    when(mockResource.getNode()).thenReturn(mockResourceNode);
    when(mockResourceNode.getSession()).thenReturn(mockSession);
    when(mockResource.getPath()).thenReturn(RDF_PATH);

    idTranslator = new DefaultIdentifierTranslator(mockSession);
  }
 @Test
 public void verifyThatPropertiesAreExternal() throws RepositoryException {
   final Session session = repo.login();
   try {
     final FedoraResource object = nodeService.find(session, testFilePath());
     assertEquals(
         "There should be exactly as many visible nodes as actual files (ie, no hidden sidecar files).",
         fileForNode().getParentFile().list().length,
         getChildCount(object.getNode().getParent()));
   } finally {
     session.logout();
   }
 }
  @Test
  public void noAclTest1() throws RepositoryException {
    final String agent1 = "http://xmlns.com/foaf/0.1/Agent";

    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(new RdfStream());
    when(mockResource.getPath()).thenReturn("/");
    when(mockResource.getTypes())
        .thenReturn(Arrays.asList(URI.create(REPOSITORY_NAMESPACE + "Resource")));
    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertEquals("There should be exactly one agent", 1, roles.size());
    assertEquals("The agent should have zero modes", 0, roles.get(agent1).size());
  }
  protected void replaceResourceWithStream(
      final FedoraResource resource,
      final InputStream requestBodyStream,
      final MediaType contentType,
      final RdfStream resourceTriples)
      throws MalformedRdfException {
    final Lang format = contentTypeToLang(contentType.toString());

    final Model inputModel = createDefaultModel();
    try {
      inputModel.read(
          requestBodyStream, getUri(resource).toString(), format.getName().toUpperCase());

    } catch (final RiotException e) {
      throw new BadRequestException("RDF was not parsable: " + e.getMessage(), e);

    } catch (final RuntimeIOException e) {
      if (e.getCause() instanceof JsonParseException) {
        throw new MalformedRdfException(e.getCause());
      }
      throw new RepositoryRuntimeException(e);
    }

    resource.replaceProperties(translator(), inputModel, resourceTriples);
  }
  private static void evaluateRequestPreconditions(
      final Request request,
      final HttpServletResponse servletResponse,
      final FedoraResource resource,
      final Session session,
      final boolean cacheControl) {

    final String txId = TransactionServiceImpl.getCurrentTransactionId(session);
    if (txId != null) {
      // Force cache revalidation if in a transaction
      servletResponse.addHeader(CACHE_CONTROL, "must-revalidate");
      servletResponse.addHeader(CACHE_CONTROL, "max-age=0");
      return;
    }

    final EntityTag etag = new EntityTag(resource.getEtagValue());
    final Date date = resource.getLastModifiedDate();
    final Date roundedDate = new Date();

    if (date != null) {
      roundedDate.setTime(date.getTime() - date.getTime() % 1000);
    }

    Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
    if (builder != null) {
      builder = builder.entity("ETag mismatch");
    } else {
      builder = request.evaluatePreconditions(roundedDate);
      if (builder != null) {
        builder = builder.entity("Date mismatch");
      }
    }

    if (builder != null && cacheControl) {
      final CacheControl cc = new CacheControl();
      cc.setMaxAge(0);
      cc.setMustRevalidate(true);
      // here we are implicitly emitting a 304
      // the exception is not an error, it's genuinely
      // an exceptional condition
      builder = builder.cacheControl(cc).lastModified(date).tag(etag);
    }
    if (builder != null) {
      throw new WebApplicationException(builder.build());
    }
  }
  @Test
  public void acl02Test() throws RepositoryException {
    final String agent = "Editors";
    final String accessTo = "/box/bag/collection";
    final String acl = "/acls/02";
    final String auth = acl + "/authorization.ttl";

    when(mockNodeService.find(mockSession, acl)).thenReturn(mockAclResource);
    when(mockProperty.getString()).thenReturn(acl);
    when(mockAclResource.getPath()).thenReturn(acl);
    when(mockResource.getPath()).thenReturn(accessTo);
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getResourceRdfStream(accessTo, acl));

    when(mockAuthorizationResource1.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource1.getPath()).thenReturn(auth);
    when(mockAuthorizationResource1.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth, TTL));

    when(mockAclResource.getChildren())
        .thenReturn(Arrays.asList(mockAuthorizationResource1).iterator());

    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertEquals("There should be exactly one agent in the role map", 1, roles.size());
    assertEquals("The agent should have exactly two modes", 2, roles.get(agent).size());
    assertTrue(
        "The agent should be able to read", roles.get(agent).contains(WEBAC_MODE_READ_VALUE));
    assertTrue(
        "The agent should be able to write", roles.get(agent).contains(WEBAC_MODE_WRITE_VALUE));
  }
  @Test
  public void acl01Test2() throws RepositoryException {
    final String accessTo = "/webacl_box2";
    final String acl = "/acls/01";
    final String auth = acl + "/authorization.ttl";

    when(mockNodeService.find(mockSession, acl)).thenReturn(mockAclResource);
    when(mockProperty.getString()).thenReturn(acl);
    when(mockAclResource.getPath()).thenReturn(acl);
    when(mockResource.getPath()).thenReturn(accessTo);
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getResourceRdfStream(accessTo, acl));

    when(mockAuthorizationResource1.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource1.getPath()).thenReturn(auth);
    when(mockAuthorizationResource1.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth, TTL));

    when(mockAclResource.getChildren())
        .thenReturn(Arrays.asList(mockAuthorizationResource1).iterator());

    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertTrue("There should be no agents associated with this object", roles.isEmpty());
  }
  @Test
  public void noAclTestMalformedRdf2() throws RepositoryException {
    final String agent1 = "http://xmlns.com/foaf/0.1/Agent";

    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(new RdfStream());
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(new RdfStream());
    when(mockResource.getPath()).thenReturn("/");
    when(mockResource.getTypes())
        .thenReturn(Arrays.asList(URI.create(REPOSITORY_NAMESPACE + "Resource")));

    System.setProperty(ROOT_AUTHORIZATION_PROPERTY, "./target/test-classes/logback-test.xml");
    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);
    System.clearProperty(ROOT_AUTHORIZATION_PROPERTY);

    assertEquals("There should be exactly one agent", 1, roles.size());
    assertEquals("The agent should have zero modes", 0, roles.get(agent1).size());
  }
  @Test
  public void noAclTest() throws RepositoryException {
    final String accessTo = "/dark/archive/sunshine";

    when(mockResource.getPath()).thenReturn(accessTo);
    when(mockResource.getContainer()).thenReturn(mockParentResource);
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(new RdfStream());
    when(mockNode.getDepth()).thenReturn(1);

    when(mockParentResource.getNode()).thenReturn(mockParentNode);
    when(mockParentResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(new RdfStream());
    when(mockParentNode.getDepth()).thenReturn(0);

    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertTrue("There should be no agents in the roles map", roles.isEmpty());
  }
  @Test
  public void acl04Test() throws RepositoryException {
    final String agent1 = "http://xmlns.com/foaf/0.1/Agent";
    final String agent2 = "Editors";
    final String accessTo = "/public_collection";
    final String acl = "/acls/04";
    final String auth1 = acl + "/auth1.ttl";
    final String auth2 = acl + "/auth2.ttl";

    when(mockNodeService.find(mockSession, acl)).thenReturn(mockAclResource);
    when(mockProperty.getString()).thenReturn(acl);
    when(mockAclResource.getPath()).thenReturn(acl);
    when(mockResource.getPath()).thenReturn(accessTo);
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getResourceRdfStream(accessTo, acl));

    when(mockAuthorizationResource1.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource1.getPath()).thenReturn(auth1);
    when(mockAuthorizationResource1.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth1, TTL));

    when(mockAuthorizationResource2.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource2.getPath()).thenReturn(auth2);
    when(mockAuthorizationResource2.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth2, TTL));

    when(mockAclResource.getChildren())
        .thenReturn(
            Arrays.asList(mockAuthorizationResource1, mockAuthorizationResource2).iterator());

    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertEquals("There should be exactly two agents", 2, roles.size());
    assertEquals("The agent should have one mode", 1, roles.get(agent1).size());
    assertTrue(
        "The agent should be able to read", roles.get(agent1).contains(WEBAC_MODE_READ_VALUE));
    assertEquals("The agent should have two modes", 2, roles.get(agent2).size());
    assertTrue(
        "The agent should be able to read", roles.get(agent2).contains(WEBAC_MODE_READ_VALUE));
    assertTrue(
        "The agent should be able to write", roles.get(agent2).contains(WEBAC_MODE_READ_VALUE));
  }
  @Test
  public void noAclTestOkRdf3() throws RepositoryException {
    final String agent1 = "testAdminUser";

    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(new RdfStream());
    when(mockResource.getPath()).thenReturn("/");
    when(mockResource.getTypes())
        .thenReturn(Arrays.asList(URI.create(REPOSITORY_NAMESPACE + "Resource")));

    System.setProperty(
        ROOT_AUTHORIZATION_PROPERTY, "./target/test-classes/test-root-authorization.ttl");
    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);
    System.clearProperty(ROOT_AUTHORIZATION_PROPERTY);

    assertEquals("There should be exactly one agent", 1, roles.size());
    assertEquals("The agent should have one mode", 1, roles.get(agent1).size());
    assertTrue(
        "The agent should be able to read", roles.get(agent1).contains(WEBAC_MODE_READ_VALUE));
  }
 protected void patchResourcewithSparql(
     final FedoraResource resource, final String requestBody, final RdfStream resourceTriples)
     throws MalformedRdfException, AccessDeniedException {
   if (resource instanceof NonRdfSourceDescription) {
     // update the described resource instead
     ((NonRdfSourceDescription) resource)
         .getDescribedResource()
         .updateProperties(translator(), requestBody, resourceTriples);
   } else {
     resource.updateProperties(translator(), requestBody, resourceTriples);
   }
 }
  /**
   * Add any resource-specific headers to the response
   *
   * @param resource the resource
   */
  protected void addResourceHttpHeaders(final FedoraResource resource) {
    if (resource instanceof FedoraBinary) {

      final FedoraBinary binary = (FedoraBinary) resource;
      final ContentDisposition contentDisposition =
          ContentDisposition.type("attachment")
              .fileName(binary.getFilename())
              .creationDate(binary.getCreatedDate())
              .modificationDate(binary.getLastModifiedDate())
              .size(binary.getContentSize())
              .build();

      servletResponse.addHeader("Content-Type", binary.getMimeType());
      servletResponse.addHeader("Content-Length", String.valueOf(binary.getContentSize()));
      servletResponse.addHeader("Accept-Ranges", "bytes");
      servletResponse.addHeader("Content-Disposition", contentDisposition.toString());
    }

    servletResponse.addHeader("Link", "<" + LDP_NAMESPACE + "Resource>;rel=\"type\"");

    if (resource instanceof NonRdfSource) {
      servletResponse.addHeader("Link", "<" + LDP_NAMESPACE + "NonRDFSource>;rel=\"type\"");
    } else if (resource instanceof Container) {
      servletResponse.addHeader("Link", "<" + CONTAINER.getURI() + ">;rel=\"type\"");
      if (resource.hasType(LDP_BASIC_CONTAINER)) {
        servletResponse.addHeader("Link", "<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\"");
      } else if (resource.hasType(LDP_DIRECT_CONTAINER)) {
        servletResponse.addHeader("Link", "<" + DIRECT_CONTAINER.getURI() + ">;rel=\"type\"");
      } else if (resource.hasType(LDP_INDIRECT_CONTAINER)) {
        servletResponse.addHeader("Link", "<" + INDIRECT_CONTAINER.getURI() + ">;rel=\"type\"");
      } else {
        servletResponse.addHeader("Link", "<" + BASIC_CONTAINER.getURI() + ">;rel=\"type\"");
      }
    } else {
      servletResponse.addHeader("Link", "<" + LDP_NAMESPACE + "RDFSource>;rel=\"type\"");
    }
    if (httpHeaderInject != null) {
      httpHeaderInject.addHttpHeaderToResponseStream(servletResponse, uriInfo, resource());
    }
  }
  @Before
  public void setUp() throws RepositoryException {

    roleProvider = new WebACRolesProvider();
    setField(roleProvider, "nodeService", mockNodeService);
    setField(roleProvider, "sessionFactory", mockSessionFactory);

    when(mockNodeService.cast(mockNode)).thenReturn(mockResource);
    when(mockNode.getSession()).thenReturn(mockSession);
    when(mockSessionFactory.getInternalSession()).thenReturn(mockSession);

    when(mockResource.getNode()).thenReturn(mockNode);
    when(mockNode.getDepth()).thenReturn(0);
  }
  @Test
  public void acl03Test2() throws RepositoryException {
    final String agent = "Restricted";
    final String accessTo = "/dark/archive";
    final String acl = "/acls/03";
    final String auth1 = acl + "/auth_restricted.ttl";
    final String auth2 = acl + "/auth_open.ttl";

    when(mockNodeService.find(mockSession, acl)).thenReturn(mockAclResource);
    when(mockProperty.getString()).thenReturn(acl);
    when(mockAclResource.getPath()).thenReturn(acl);
    when(mockResource.getPath()).thenReturn(accessTo);
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getResourceRdfStream(accessTo, acl));

    when(mockAuthorizationResource1.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource1.getPath()).thenReturn(auth1);
    when(mockAuthorizationResource1.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth1, TTL));

    when(mockAuthorizationResource2.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource2.getPath()).thenReturn(auth2);
    when(mockAuthorizationResource2.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth2, TTL));

    when(mockAclResource.getChildren())
        .thenReturn(
            Arrays.asList(mockAuthorizationResource1, mockAuthorizationResource2).iterator());

    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertEquals("There should be exactly one agent", 1, roles.size());
    assertEquals("The agent should have one mode", 1, roles.get(agent).size());
    assertTrue(
        "The agent should be able to read", roles.get(agent).contains(WEBAC_MODE_READ_VALUE));
  }
  /* (non-Javadoc)
   * Test that an in-repository resource used as a target for acl:agentClass has
   * the rdf:type of foaf:Group. This test mocks a resource that is not of the type
   * foaf:Group and therefore should retrieve zero agents.
   */
  @Test
  public void acl09Test2() throws RepositoryException {
    final String agent1 = "person1";
    final String agent2 = "person2";
    final String accessTo = "/anotherCollection";

    final String groupResource = "/group/foo";
    final String acl = "/acls/09";
    final String auth = acl + "/authorization.ttl";
    final String group = acl + "/group.ttl";

    when(mockNodeService.find(mockSession, acl)).thenReturn(mockAclResource);
    when(mockNodeService.find(mockSession, groupResource)).thenReturn(mockAgentClassResource);
    when(mockProperty.getString()).thenReturn(acl);
    when(mockAclResource.getPath()).thenReturn(acl);
    when(mockResource.getPath()).thenReturn(accessTo);
    when(mockResource.getTypes()).thenReturn(new ArrayList<>());
    when(mockResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getResourceRdfStream(accessTo, acl));

    when(mockAuthorizationResource1.getTypes()).thenReturn(Arrays.asList(WEBAC_AUTHORIZATION));
    when(mockAuthorizationResource1.getPath()).thenReturn(auth);
    when(mockAuthorizationResource1.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(auth, TTL));

    when(mockAgentClassResource.getTypes()).thenReturn(new ArrayList<>());
    when(mockAgentClassResource.getPath()).thenReturn(groupResource);
    when(mockAgentClassResource.getTriples(anyObject(), eq(PropertiesRdfContext.class)))
        .thenReturn(getRdfStreamFromResource(group, TTL));

    when(mockAclResource.getChildren())
        .thenReturn(Arrays.asList(mockAuthorizationResource1).iterator());

    final Map<String, List<String>> roles = roleProvider.getRoles(mockNode, true);

    assertEquals("There should be exactly zero agents", 0, roles.size());
  }
 protected RdfStream getTriples(
     final FedoraResource resource, final Class<? extends RdfStream> x) {
   return resource.getTriples(translator(), x);
 }