@Test(expected = AccessDeniedException.class)
 public void accessIsDeniedIfPermissionIsNotGranted() {
   AclService service = mock(AclService.class);
   Acl acl = mock(Acl.class);
   when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(false);
   // Try a second time with no permissions found
   when(acl.isGranted(any(List.class), any(List.class), anyBoolean()))
       .thenThrow(new NotFoundException(""));
   when(service.readAclById(any(ObjectIdentity.class), any(List.class))).thenReturn(acl);
   AclEntryAfterInvocationProvider provider =
       new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
   provider.setProcessConfigAttribute("MY_ATTRIBUTE");
   provider.setMessageSource(new SpringSecurityMessageSource());
   provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
   provider.setProcessDomainObjectClass(Object.class);
   provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
   try {
     provider.decide(
         mock(Authentication.class),
         new Object(),
         SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"),
         new Object());
     fail("Expected Exception");
   } catch (AccessDeniedException expected) {
   }
   // Second scenario with no acls found
   provider.decide(
       mock(Authentication.class),
       new Object(),
       SecurityConfig.createList("UNSUPPORTED", "MY_ATTRIBUTE"),
       new Object());
 }
  private String getTenant(long aclId, long aclChangeSetId) {
    String tenantDomain = getAclTenant(aclId);
    if (tenantDomain == null) {
      List<Long> aclChangeSetIds = new ArrayList<Long>(1);
      aclChangeSetIds.add(aclChangeSetId);

      List<Acl> acls = solrDAO.getAcls(aclChangeSetIds, null, 1024);
      for (Acl acl : acls) {
        tenantDomain = getAclTenant(acl.getId());
        if (tenantDomain != null) {
          break;
        }
      }

      if (tenantDomain == null) {
        // tenant not found - log warning ?
        tenantDomain = null; // temp - for debug breakpoint only
      }
    }
    return tenantDomain;
  }
  @Test
  public void accessIsAllowedIfPermissionIsGranted() {
    AclService service = mock(AclService.class);
    Acl acl = mock(Acl.class);
    when(acl.isGranted(any(List.class), any(List.class), anyBoolean())).thenReturn(true);
    when(service.readAclById(any(ObjectIdentity.class), any(List.class))).thenReturn(acl);
    AclEntryAfterInvocationProvider provider =
        new AclEntryAfterInvocationProvider(service, Arrays.asList(mock(Permission.class)));
    provider.setMessageSource(new SpringSecurityMessageSource());
    provider.setObjectIdentityRetrievalStrategy(mock(ObjectIdentityRetrievalStrategy.class));
    provider.setProcessDomainObjectClass(Object.class);
    provider.setSidRetrievalStrategy(mock(SidRetrievalStrategy.class));
    Object returned = new Object();

    assertThat(returned)
        .isSameAs(
            provider.decide(
                mock(Authentication.class),
                new Object(),
                SecurityConfig.createList("AFTER_ACL_READ"),
                returned));
  }
  @Test
  public void testCRUDAcl() throws NiciraNvpApiException {
    Acl acl = new Acl();
    acl.setDisplayName("Acl" + timestamp);

    // Note that if the protocol is 6 (TCP) then you cannot put ICMP code and type
    // Note that if the protocol is 1 (ICMP) then you cannot put ports
    final List<AclRule> egressRules = new ArrayList<AclRule>();
    acl.setLogicalPortEgressRules(egressRules);
    egressRules.add(
        new AclRule(
            AclRule.ETHERTYPE_IPV4,
            1,
            "allow",
            null,
            null,
            "1.10.10.0",
            "1.10.10.1",
            null,
            null,
            null,
            null,
            0,
            0,
            5));
    egressRules.add(
        new AclRule(
            AclRule.ETHERTYPE_IPV4,
            6,
            "allow",
            null,
            null,
            "1.10.10.6",
            "1.10.10.7",
            80,
            80,
            80,
            80,
            1,
            null,
            null));

    final List<AclRule> ingressRules = new ArrayList<AclRule>();
    acl.setLogicalPortIngressRules(ingressRules);
    ingressRules.add(
        new AclRule(
            AclRule.ETHERTYPE_IPV4,
            1,
            "allow",
            null,
            null,
            "1.10.10.0",
            "1.10.10.1",
            null,
            null,
            null,
            null,
            0,
            0,
            5));
    ingressRules.add(
        new AclRule(
            AclRule.ETHERTYPE_IPV4,
            6,
            "allow",
            null,
            null,
            "1.10.10.6",
            "1.10.10.7",
            80,
            80,
            80,
            80,
            1,
            null,
            null));

    final List<NiciraNvpTag> tags = new ArrayList<NiciraNvpTag>();
    acl.setTags(tags);
    tags.add(new NiciraNvpTag("nvp", "MyTag1"));
    tags.add(new NiciraNvpTag("nicira", "MyTag2"));
    // In the creation we don't get to specify UUID, href or schema: they don't exist yet

    try {
      acl = api.createAcl(acl);

      // We can now update the new entity
      acl.setDisplayName("UpdatedAcl" + timestamp);
      api.updateAcl(acl, acl.getUuid());

      // Read them all
      NiciraNvpList<Acl> acls = api.findAcl();
      Acl scInList = null;
      for (final Acl iAcl : acls.getResults()) {
        if (iAcl.getUuid().equalsIgnoreCase(acl.getUuid())) {
          scInList = iAcl;
        }
      }
      assertEquals("Read a ACL different from the one just created and updated", acl, scInList);

      // Read them filtered by uuid (get one)
      acls = api.findAcl(acl.getUuid());
      assertEquals(
          "Read a ACL different from the one just created and updated",
          acl,
          acls.getResults().get(0));
      assertEquals(
          "Read a ACL filtered by unique id (UUID) with more than one item",
          1,
          acls.getResults().size());

      // We can now delete the new entity
      api.deleteAcl(acl.getUuid());
    } catch (final NiciraNvpApiException e) {
      e.printStackTrace();
      assertTrue("Errors in ACL CRUD", false);
    }
  }
public class SerializationTest extends BaseSerializationTest {

  private static final Storage STORAGE =
      StorageOptions.newBuilder().setProjectId("p").build().getService();
  private static final Acl.Domain ACL_DOMAIN = new Acl.Domain("domain");
  private static final Acl.Group ACL_GROUP = new Acl.Group("group");
  private static final Acl.Project ACL_PROJECT_ = new Acl.Project(ProjectRole.VIEWERS, "pid");
  private static final Acl.User ACL_USER = new Acl.User("user");
  private static final Acl.RawEntity ACL_RAW = new Acl.RawEntity("raw");
  private static final Acl ACL = Acl.of(ACL_DOMAIN, Acl.Role.OWNER);
  private static final BlobInfo BLOB_INFO = BlobInfo.newBuilder("b", "n").build();
  private static final BucketInfo BUCKET_INFO = BucketInfo.of("b");
  private static final Blob BLOB = new Blob(STORAGE, new BlobInfo.BuilderImpl(BLOB_INFO));
  private static final Bucket BUCKET = new Bucket(STORAGE, new BucketInfo.BuilderImpl(BUCKET_INFO));
  private static final Cors.Origin ORIGIN = Cors.Origin.any();
  private static final Cors CORS =
      Cors.newBuilder().setMaxAgeSeconds(1).setOrigins(Collections.singleton(ORIGIN)).build();
  private static final PageImpl<Blob> PAGE_RESULT =
      new PageImpl<>(null, "c", Collections.singletonList(BLOB));
  private static final StorageException STORAGE_EXCEPTION = new StorageException(42, "message");
  private static final Storage.BlobListOption BLOB_LIST_OPTIONS =
      Storage.BlobListOption.pageSize(100);
  private static final Storage.BlobSourceOption BLOB_SOURCE_OPTIONS =
      Storage.BlobSourceOption.generationMatch(1);
  private static final Storage.BlobTargetOption BLOB_TARGET_OPTIONS =
      Storage.BlobTargetOption.generationMatch();
  private static final Storage.BucketListOption BUCKET_LIST_OPTIONS =
      Storage.BucketListOption.prefix("bla");
  private static final Storage.BucketSourceOption BUCKET_SOURCE_OPTIONS =
      Storage.BucketSourceOption.metagenerationMatch(1);
  private static final Storage.BucketTargetOption BUCKET_TARGET_OPTIONS =
      Storage.BucketTargetOption.metagenerationNotMatch();
  private static final Map<StorageRpc.Option, ?> EMPTY_RPC_OPTIONS = ImmutableMap.of();

  @Override
  protected Serializable[] serializableObjects() {
    StorageOptions options =
        StorageOptions.newBuilder()
            .setProjectId("p1")
            .setCredentials(NoCredentials.getInstance())
            .build();
    StorageOptions otherOptions = options.toBuilder().setProjectId("p2").build();
    return new Serializable[] {
      ACL_DOMAIN,
      ACL_GROUP,
      ACL_PROJECT_,
      ACL_USER,
      ACL_RAW,
      ACL,
      BLOB_INFO,
      BLOB,
      BUCKET_INFO,
      BUCKET,
      ORIGIN,
      CORS,
      PAGE_RESULT,
      BLOB_LIST_OPTIONS,
      BLOB_SOURCE_OPTIONS,
      BLOB_TARGET_OPTIONS,
      BUCKET_LIST_OPTIONS,
      BUCKET_SOURCE_OPTIONS,
      BUCKET_TARGET_OPTIONS,
      STORAGE_EXCEPTION,
      options,
      otherOptions
    };
  }

  @Override
  protected Restorable<?>[] restorableObjects() {
    StorageOptions options = StorageOptions.newBuilder().setProjectId("p2").build();
    ReadChannel reader = new BlobReadChannel(options, BlobId.of("b", "n"), EMPTY_RPC_OPTIONS);
    // avoid closing when you don't want partial writes to GCS upon failure
    @SuppressWarnings("resource")
    BlobWriteChannel writer =
        new BlobWriteChannel(
            options, BlobInfo.newBuilder(BlobId.of("b", "n")).build(), "upload-id");
    return new Restorable<?>[] {reader, writer};
  }
}