text:
package com.acciente.oacc;

import org.junit.Test;

import java.util.Collections;
import java.util.Set;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

public class TestAccessControl_revokeDomainCreatePermissions extends TestAccessControlBase {
   @Test
   public void revokeDomainCreatePermissions_validAsSystemResource() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set accessor permissions
      Resource accessorResource = generateUnauthenticatableResource();
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      setOf(domCreatePerm_superuser,
                                                            domCreatePerm_create_withGrant,
                                                            domCreatePerm_child));

      Set<DomainCreatePermission> domainCreatePermissions_expected
            = setOf(domCreatePerm_superuser, domCreatePerm_create_withGrant, domCreatePerm_child);
      final Set<DomainCreatePermission> domainCreatePermissions_post = accessControlContext.getEffectiveDomainCreatePermissions(
            accessorResource);
      assertThat(domainCreatePermissions_post, is(domainCreatePermissions_expected));

      // revoke domain create permissions and verify
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create_withGrant,
                                                         domCreatePerm_child);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // test set-based version
      Resource accessorResource2 = generateUnauthenticatableResource();
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      setOf(domCreatePerm_superuser,
                                                            domCreatePerm_create_withGrant,
                                                            domCreatePerm_child));
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_expected));

      accessControlContext.revokeDomainCreatePermissions(accessorResource2,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create_withGrant,
                                                               domCreatePerm_child));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_withExtId() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set accessor permissions
      final String externalId = generateUniqueExternalId();
      Resource accessorResource = generateUnauthenticatableResourceWithExtId(externalId);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      setOf(domCreatePerm_superuser,
                                                            domCreatePerm_create_withGrant,
                                                            domCreatePerm_child));

      Set<DomainCreatePermission> domainCreatePermissions_expected
            = setOf(domCreatePerm_superuser, domCreatePerm_create_withGrant, domCreatePerm_child);
      final Set<DomainCreatePermission> domainCreatePermissions_post = accessControlContext.getEffectiveDomainCreatePermissions(
            accessorResource);
      assertThat(domainCreatePermissions_post, is(domainCreatePermissions_expected));

      // revoke domain create permissions and verify
      accessControlContext.revokeDomainCreatePermissions(Resources.getInstance(externalId),
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create_withGrant,
                                                         domCreatePerm_child);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // test set-based version
      final String externalId2 = generateUniqueExternalId();
      Resource accessorResource2 = generateUnauthenticatableResourceWithExtId(externalId2);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      setOf(domCreatePerm_superuser,
                                                            domCreatePerm_create_withGrant,
                                                            domCreatePerm_child));
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_expected));

      accessControlContext.revokeDomainCreatePermissions(Resources.getInstance(externalId2),
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create_withGrant,
                                                               domCreatePerm_child));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_validAsAuthorized() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new resource and set its domainCreatePermissions
      Resource accessorResource = generateUnauthenticatableResource();
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser, domCreatePerm_create_withGrant, domCreatePerm_child);
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource),
                 is(domainCreatePermissions_pre));

      // revoke the domain create permissions as grantor and verify
      grantQueryPermission(grantorResource, accessorResource);
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create_withGrant,
                                                         domCreatePerm_child);

      final Set<DomainCreatePermission> domainCreatePermissions_post
            = accessControlContext.getEffectiveDomainCreatePermissions(accessorResource);
      assertThat(domainCreatePermissions_post.isEmpty(), is(true));

      // test set-based version
      Resource accessorResource2 = generateUnauthenticatableResource();
      grantQueryPermission(grantorResource, accessorResource2);
      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_pre));

      // revoke and verify
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create_withGrant,
                                                               domCreatePerm_child));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_ungrantedPermissions_shouldSucceed() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new accessor resource
      Resource accessorResource = generateUnauthenticatableResource();
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // revoke the domain create permissions as grantor
      grantQueryPermission(grantorResource, accessorResource);
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create_withGrant,
                                                         domCreatePerm_child);

      final Set<DomainCreatePermission> domainCreatePermissions_post
            = accessControlContext.getEffectiveDomainCreatePermissions(accessorResource);
      assertThat(domainCreatePermissions_post.isEmpty(), is(true));

      // test set-based version
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create_withGrant,
                                                               domCreatePerm_child));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_ungrantedPermissionsWithAndWithoutGrant_shouldFail() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new accessor resource
      Resource accessorResource = generateUnauthenticatableResource();
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // revoke the domain create permissions as grantor
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                            domCreatePerm_superuser,
                                                            domCreatePerm_create_withGrant,
                                                            domCreatePerm_child);
         fail("revoking permissions without grant-authorization should have failed");
      }
      catch (NotAuthorizedException e) {
         assertThat(e.getMessage().toLowerCase(), containsString(domCreatePerm_superuser.toString().toLowerCase()));
         assertThat(e.getMessage().toLowerCase(), not(containsString(domCreatePerm_child.toString().toLowerCase())));
         assertThat(e.getMessage().toLowerCase(), not(containsString(domCreatePerm_create_withGrant.toString().toLowerCase())));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                            setOf(domCreatePerm_superuser,
                                                                  domCreatePerm_create_withGrant,
                                                                  domCreatePerm_child));
         fail("revoking permissions without grant-authorization should have failed");
      }
      catch (NotAuthorizedException e) {
         assertThat(e.getMessage().toLowerCase(), containsString(domCreatePerm_superuser.toString().toLowerCase()));
         assertThat(e.getMessage().toLowerCase(), not(containsString(domCreatePerm_child.toString().toLowerCase())));
         assertThat(e.getMessage().toLowerCase(), not(containsString(domCreatePerm_create_withGrant.toString().toLowerCase())));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_reRevokePermissions() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create
            = DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE) ;
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      Resource accessorResource = generateUnauthenticatableResource();

      // initialize domain create permissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser, domCreatePerm_create, domCreatePerm_child_withGrant);
      accessControlContext.setDomainCreatePermissions(accessorResource, domainCreatePermissions_pre);

      final Set<DomainCreatePermission> domainCreatePermissions_post = accessControlContext.getEffectiveDomainCreatePermissions(
            accessorResource);
      assertThat(domainCreatePermissions_post, is(domainCreatePermissions_pre));

      // revoke domain create permissions and verify
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create,
                                                         domCreatePerm_child_withGrant);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // revoke domain create permissions again and verify that nothing changed
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create,
                                                         domCreatePerm_child_withGrant);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // test set-based version
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create,
                                                               domCreatePerm_child_withGrant));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_revokeSubsetOfPermissions() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new resource and set its domainCreatePermissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser, domCreatePerm_create_withGrant, domCreatePerm_child);
      Resource accessorResource = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);
      Resource accessorResource2 = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource),
                 is(domainCreatePermissions_pre));

      // revoke the domain create permissions as grantor
      grantQueryPermission(grantorResource, accessorResource);
      grantQueryPermission(grantorResource, accessorResource2);
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_child);

      final Set<DomainCreatePermission> domainCreatePermissions_post
            = accessControlContext.getEffectiveDomainCreatePermissions(accessorResource);
      assertThat(domainCreatePermissions_post, is(setOf(domCreatePerm_create_withGrant)));

      // test set-based version
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_pre));
      accessControlContext.revokeDomainCreatePermissions(accessorResource2,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_child));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(setOf(domCreatePerm_create_withGrant)));
   }

   @Test
   public void revokeDomainCreatePermissions_revokeSubsetWithCreate_shouldFail() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new resource and set its domainCreatePermissions
      Resource accessorResource = generateUnauthenticatableResource();
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser, domCreatePerm_create_withGrant, domCreatePerm_child);
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource),
                 is(domainCreatePermissions_pre));

      // revoke the domain create permissions as grantor
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                            domCreatePerm_child,
                                                            domCreatePerm_create_withGrant);
         fail("revoking subset of permissions including *CREATE should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("subset of domain create permissions that includes the *create"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                            setOf(domCreatePerm_child,
                                                                  domCreatePerm_create_withGrant));
         fail("revoking subset of permissions including *CREATE should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("subset of domain create permissions that includes the *create"));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_withUnauthorizedPermissionsGrantedElsewhere_shouldFailAsAuthorized() {
      authenticateSystemResource();
      final String grantablePermissionName = DomainPermissions.CREATE_CHILD_DOMAIN;
      final String ungrantablePermissionName = DomainPermissions.SUPER_USER;
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);
      final Resource accessorResource = generateUnauthenticatableResource();

      // setup accessor permissions
      Set<DomainCreatePermission> accessorPermissions_pre
            = setOf(DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                    DomainCreatePermissions.getInstance(DomainPermissions.getInstance(ungrantablePermissionName)));

      accessControlContext.setDomainCreatePermissions(accessorResource, accessorPermissions_pre);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource), is(accessorPermissions_pre));

      // setup grantor permissions
      Set<DomainCreatePermission> grantorPermissions
            = setOf(DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE),
                    DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(grantablePermissionName)));

      accessControlContext.setDomainCreatePermissions(grantorResource, grantorPermissions);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource), is(grantorPermissions));

      // authenticate grantor resource
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));

      // attempt to revoke permissions as grantor and verify
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                            DomainCreatePermissions
                                                                  .getInstance(DomainPermissions.getInstance(
                                                                        grantablePermissionName)),
                                                            DomainCreatePermissions
                                                                  .getInstance(DomainPermissions.getInstance(
                                                                        ungrantablePermissionName)));
         fail("revoking existing domain create permission granted elsewhere without authorization should have failed");
      }
      catch (NotAuthorizedException e) {
         assertThat(e.getMessage().toLowerCase(), containsString(ungrantablePermissionName.toLowerCase()));
         assertThat(e.getMessage().toLowerCase(), not(containsString(grantablePermissionName)));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                            setOf(DomainCreatePermissions
                                                                        .getInstance(DomainPermissions.getInstance(
                                                                              grantablePermissionName)),
                                                                  DomainCreatePermissions
                                                                        .getInstance(DomainPermissions.getInstance(
                                                                              ungrantablePermissionName))));
         fail("revoking existing domain create permission granted elsewhere without authorization should have failed");
      }
      catch (NotAuthorizedException e) {
         assertThat(e.getMessage().toLowerCase(), containsString(ungrantablePermissionName.toLowerCase()));
         assertThat(e.getMessage().toLowerCase(), not(containsString(grantablePermissionName)));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_identicalPermissions_shouldSucceedAsAuthorized() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_create
            = DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new resource and set its domainCreatePermissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser, domCreatePerm_create, domCreatePerm_child_withGrant);
      Resource accessorResource = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource),
                 is(domainCreatePermissions_pre));

      // revoke the domain create permissions as grantor
      grantQueryPermission(grantorResource, accessorResource);
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create,
                                                         domCreatePerm_child_withGrant);

      final Set<DomainCreatePermission> domainCreatePermissions_post
            = accessControlContext.getEffectiveDomainCreatePermissions(accessorResource);
      assertThat(domainCreatePermissions_post.isEmpty(), is(true));

      // test set-based version
      Resource accessorResource2 = generateUnauthenticatableResource();
      grantQueryPermission(grantorResource, accessorResource2);
      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_pre));
      accessControlContext.revokeDomainCreatePermissions(accessorResource2,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create,
                                                               domCreatePerm_child_withGrant));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_lesserPermissions_shouldSucceedAsAuthorized() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_create
            = DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new resource and set its domainCreatePermissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser, domCreatePerm_create, domCreatePerm_child);
      Resource accessorResource = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource),
                 is(domainCreatePermissions_pre));

      // revoke the domain create permissions as grantor
      grantQueryPermission(grantorResource, accessorResource);
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser_withGrant,
                                                         domCreatePerm_create_withGrant,
                                                         domCreatePerm_child_withGrant);

      final Set<DomainCreatePermission> domainCreatePermissions_post
            = accessControlContext.getEffectiveDomainCreatePermissions(accessorResource);
      assertThat(domainCreatePermissions_post.isEmpty(), is(true));

      // test set-based version
      Resource accessorResource2 = generateUnauthenticatableResource();
      grantQueryPermission(grantorResource, accessorResource2);
      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_pre));

      accessControlContext.revokeDomainCreatePermissions(accessorResource2,
                                                         setOf(domCreatePerm_superuser_withGrant,
                                                            domCreatePerm_create_withGrant,
                                                            domCreatePerm_child_withGrant));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_greaterPermissions_shouldSucceedAsAuthorized() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_superuser_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_superuser
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_create
            = DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE);
      final DomainCreatePermission domCreatePerm_child_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));
      final DomainCreatePermission domCreatePerm_child
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.CREATE_CHILD_DOMAIN));

      // set up an authenticatable resource with resource class create permission
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);

      final Set<DomainCreatePermission> domainCreatePermissions_granter
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);

      // set domain create permissions and verify
      accessControlContext.setDomainCreatePermissions(grantorResource, domainCreatePermissions_granter);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource),
                 is(domainCreatePermissions_granter));

      // now create a new resource and set its domainCreatePermissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(domCreatePerm_superuser_withGrant, domCreatePerm_create_withGrant, domCreatePerm_child_withGrant);
      Resource accessorResource = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource),
                 is(domainCreatePermissions_pre));

      // revoke the domain create permissions as grantor
      grantQueryPermission(grantorResource, accessorResource);
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser,
                                                         domCreatePerm_create,
                                                         domCreatePerm_child);

      final Set<DomainCreatePermission> domainCreatePermissions_post
            = accessControlContext.getEffectiveDomainCreatePermissions(accessorResource);
      assertThat(domainCreatePermissions_post.isEmpty(), is(true));

      // test set-based version
      Resource accessorResource2 = generateUnauthenticatableResource();
      grantQueryPermission(grantorResource, accessorResource2);
      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      domainCreatePermissions_pre);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2),
                 is(domainCreatePermissions_pre));

      accessControlContext.revokeDomainCreatePermissions(accessorResource2,
                                                         setOf(domCreatePerm_superuser,
                                                               domCreatePerm_create,
                                                               domCreatePerm_child));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_whitespaceConsistent() {
      authenticateSystemResource();

      final DomainCreatePermission domCreatePerm_superuser_trailingspaces
            = DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER + " \t"));
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(" \t" + DomainCreatePermissions.CREATE);

      // todo: arguably, system permissions should match in name exactly, but the API uses Strings, not Enums, and is otherwise whitespace-consistent
      //       this could pose some complications depending on if the system permission name is persisted from the passed string or derived from an authoritative source
      // set accessor permissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE),
                    DomainCreatePermissions.getInstance(DomainPermissions.getInstance(DomainPermissions.SUPER_USER)));
      Resource accessorResource = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource), is(
            domainCreatePermissions_pre));

      // revoke domain create permissions and verify
      accessControlContext.revokeDomainCreatePermissions(accessorResource,
                                                         domCreatePerm_superuser_trailingspaces,
                                                         domCreatePerm_create_withGrant);

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource).isEmpty(), is(true));

      // test set-based version
      Resource accessorResource2 = generateUnauthenticatableResource();
      accessControlContext.setDomainCreatePermissions(accessorResource2,
                                                      domainCreatePermissions_pre);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2), is(domainCreatePermissions_pre));

      accessControlContext.revokeDomainCreatePermissions(accessorResource2,
                                                         setOf(domCreatePerm_superuser_trailingspaces,
                                                               domCreatePerm_create_withGrant));

      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(accessorResource2).isEmpty(), is(true));
   }

   @Test
   public void revokeDomainCreatePermissions_nulls_shouldFail() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);

      Resource accessorResource = generateUnauthenticatableResource();

      // attempt to revoke domain create permissions with nulls
      try {
         accessControlContext.revokeDomainCreatePermissions(null, domCreatePerm_create_withGrant);
         fail("revoking domain create permissions with null accessor resource should have failed");
      }
      catch (NullPointerException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("resource required"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(Resources.getInstance(null), domCreatePerm_create_withGrant);
         fail("revoking domain create permissions with null internal/external resource ids should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("resource id and/or external id is required"));
      }

      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource, (DomainCreatePermission) null);
         fail("revoking domain create permissions with null domain permission set should have failed");
      }
      catch (NullPointerException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("permission required"));
      }

      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource, domCreatePerm_create_withGrant, null);
         fail("revoking domain create permissions with null element in domain permission set should have failed");
      }
      catch (NullPointerException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("an array or a sequence"));
      }

      try {
         accessControlContext.revokeDomainCreatePermissions(null, setOf(domCreatePerm_create_withGrant));
         fail("revoking domain create permissions with null accessor resource should have failed");
      }
      catch (NullPointerException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("resource required"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(Resources.getInstance(null),
                                                            setOf(domCreatePerm_create_withGrant));
         fail("revoking domain create permissions with null internal/external resource ids should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("resource id and/or external id is required"));
      }

      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource, (Set<DomainCreatePermission>) null);
         fail("revoking domain create permissions with null domain permission set should have failed");
      }
      catch (NullPointerException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("permissions required"));
      }

      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource, setOf(domCreatePerm_create_withGrant, null));
         fail("revoking domain create permissions with null element in domain permission set should have failed");
      }
      catch (NullPointerException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("contains null element"));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_emptyPermissionSet_shouldFail() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);

      Resource accessorResource = generateUnauthenticatableResource();

      // attempt to revoke domain create permissions with nulls
      try {
         accessControlContext.revokeDomainCreatePermissions(accessorResource, Collections.<DomainCreatePermission>emptySet());
         fail("revoking domain create permissions with null domain permission set should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("permissions required"));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_duplicateIdenticalPermissions_shouldFail() {
      authenticateSystemResource();
      final String grantedPermissionName = DomainPermissions.CREATE_CHILD_DOMAIN;
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);
      final Resource accessorResource = generateUnauthenticatableResource();

      // set accessor permissions
      Set<DomainCreatePermission> domainCreatePermissions_pre
            = setOf(DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                    DomainCreatePermissions.getInstance(DomainPermissions.getInstance(grantedPermissionName)));
      accessControlContext.setDomainCreatePermissions(accessorResource,
                                                      domainCreatePermissions_pre);

      // setup grantor permissions WITHOUT grantable *CREATE
      Set<DomainCreatePermission> grantorPermissions
            = setOf(DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE),
                    DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(grantedPermissionName)));

      accessControlContext.setDomainCreatePermissions(grantorResource, grantorPermissions);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource), is(grantorPermissions));

      // authenticate grantor resource
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));

      // revoke duplicate permissions and verify
      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                              DomainCreatePermissions
                                                    .getInstance(DomainPermissions.getInstance(grantedPermissionName)),
                                              DomainCreatePermissions
                                                    .getInstance(DomainPermissions.getInstance(grantedPermissionName)));
         fail("revoking create permissions that include duplicate (identical) permissions, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate element"));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_duplicatePermissions_shouldFail() {
      authenticateSystemResource();
      final String grantedPermissionName = DomainPermissions.CREATE_CHILD_DOMAIN;
      final char[] password = generateUniquePassword();
      final Resource grantorResource = generateAuthenticatableResource(password);
      final Resource accessorResource = generateUnauthenticatableResource();

      // setup grantor permissions
      Set<DomainCreatePermission> grantorPermissions
            = setOf(DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE),
                    DomainCreatePermissions.getInstanceWithGrantOption(DomainPermissions.getInstance(grantedPermissionName)));

      accessControlContext.setDomainCreatePermissions(grantorResource, grantorPermissions);
      assertThat(accessControlContext.getEffectiveDomainCreatePermissions(grantorResource), is(grantorPermissions));

      // authenticate grantor resource
      accessControlContext.authenticate(grantorResource, PasswordCredentials.newInstance(password));

      // attempt to revoke duplicate permissions and verify
      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                              DomainCreatePermissions
                                                    .getInstance(DomainPermissions.getInstance(grantedPermissionName)),
                                              DomainCreatePermissions
                                                    .getInstanceWithGrantOption(DomainPermissions.getInstance(grantedPermissionName)));
         fail("revoking create permissions that include the same permission - by name - but with different grant-options, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate permission"));
      }
      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                              DomainCreatePermissions
                                                    .getInstance(DomainPermissions.getInstance(grantedPermissionName)),
                                              DomainCreatePermissions
                                                    .getInstance(DomainPermissions.getInstanceWithGrantOption(grantedPermissionName)));
         fail("revoking create permissions that include the same permission - by name - but with different grant-options, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate permission"));
      }
      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                              DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE));
         fail("revoking create permissions that include the same permission - by name - but with different grant-options, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate permission"));
      }

      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              setOf(DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                                    DomainCreatePermissions
                                                          .getInstance(DomainPermissions.getInstance(
                                                                grantedPermissionName)),
                                                    DomainCreatePermissions
                                                          .getInstanceWithGrantOption(DomainPermissions.getInstance(
                                                                grantedPermissionName))));
         fail("revoking create permissions that include the same permission - by name - but with different grant-options, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate permission"));
      }
      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              setOf(DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                                    DomainCreatePermissions
                                                          .getInstance(DomainPermissions.getInstance(
                                                                grantedPermissionName)),
                                                    DomainCreatePermissions
                                                          .getInstance(DomainPermissions.getInstanceWithGrantOption(
                                                                grantedPermissionName))));
         fail("revoking create permissions that include the same permission - by name - but with different grant-options, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate permission"));
      }
      try {
         accessControlContext
               .revokeDomainCreatePermissions(accessorResource,
                                              setOf(DomainCreatePermissions.getInstance(DomainCreatePermissions.CREATE),
                                                    DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE)));
         fail("revoking create permissions that include the same permission - by name - but with different grant-options, should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("duplicate permission"));
      }
   }

   @Test
   public void revokeDomainCreatePermissions_nonExistentReferences_shouldFail() {
      authenticateSystemResource();
      final DomainCreatePermission domCreatePerm_create_withGrant
            = DomainCreatePermissions.getInstanceWithGrantOption(DomainCreatePermissions.CREATE);
      final Resource invalidResource = Resources.getInstance(-999L);
      final Resource invalidExternalResource = Resources.getInstance("invalid");
      final Resource mismatchedResource = Resources.getInstance(-999L, "invalid");

      // attempt to revoke domain create permissions with non-existent references
      try {
         accessControlContext.revokeDomainCreatePermissions(invalidResource, domCreatePerm_create_withGrant);
         fail("revoking domain create permissions with non-existent accessor resource reference should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("not found"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(invalidExternalResource, domCreatePerm_create_withGrant);
         fail("revoking domain create permissions with non-existent external accessor resource reference should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("not found"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(mismatchedResource, domCreatePerm_create_withGrant);
         fail("revoking domain create permissions with mismatched internal/external accessor resource reference should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("not resolve"));
      }

      try {
         accessControlContext.revokeDomainCreatePermissions(invalidResource,
                                                            setOf(domCreatePerm_create_withGrant));
         fail("revoking domain create permissions with non-existent accessor resource reference should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("not found"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(invalidExternalResource,
                                                            setOf(domCreatePerm_create_withGrant));
         fail("revoking domain create permissions with non-existent external accessor resource reference should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("not found"));
      }
      try {
         accessControlContext.revokeDomainCreatePermissions(mismatchedResource,
                                                            setOf(domCreatePerm_create_withGrant));
         fail("revoking domain create permissions with mismatched internal/external accessor resource reference should have failed");
      }
      catch (IllegalArgumentException e) {
         assertThat(e.getMessage().toLowerCase(), containsString("not resolve"));
      }
   }
}


text:
Core
====

:mod:`flask_swag.core` module is set of simple swagger spec generation utilities.

Each dict generators are generated by marshmallow schemas in
:mod:`flask_swag.schemas` and follow
`swagger specification <http://swagger.io/specification/>`_

Generation & Dumping
--------------------

You can generate swagger root object like ::

    from flask.ext.core import Swagger, Info

    generated = Swagger(
        version="2.0",
        info=Info(
            title="Some title.",
            version="0.1.0",
        ),
    )

And you can dump generated swagger root object like ::

    from flask.ext.core import dump

    dumped = dump(generated)

Strict Mode
-----------

By default, generators cannot accept unexpected fields,
but, with ``_strict=False`` option, you can add additional fields to swagger objects ::

    generated = Swagger(
        version="2.0",
        info=Info(
            title="Some title.",
            version="0.1.0",
        ),
        foo='bar',
        _strict=False,
    )

redpajama_set_name: RedPajamaGithub


text:
typedef unsigned char _Bool;
#define bool	_Bool
#define false	0
#define true	1

#endif


text:
set -evx

sed -i -r "s/^(\s*)VERSION = \".+\"/\1VERSION = \"$(cat VERSION)\"/" lib/knife-push/version.rb

# Once Expeditor finshes executing this script, it will commit the changes and push
# the commit as a new tag corresponding to the value in the VERSION file.


text:
class AddDeletedAtToTransferItems < ActiveRecord::Migration[4.2]
  def change
    add_column :spree_transfer_items, :deleted_at, :datetime
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>New Study Reveals Lungs Play A Key Role In Blood Production</title>
    <meta name="description" content="" />
    <link href="//fonts.googleapis.com/css?family=Noto+Sans:300,400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Noto+Serif:400,700,400italic" rel="stylesheet" type="text/css">
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="//alchemistcookbook.github.io/themes/saga/assets/css/style.css?v=1490638848422" rel="stylesheet" type="text/css">
    <link href="//alchemistcookbook.github.io/themes/saga/assets/css/animate.min.css?v=1490638848422" rel="stylesheet" type="text/css">
    <link href="https://alchemistcookbook.github.io/favicon.ico" rel="shortcut icon">
    <link rel="canonical" href="https://alchemistcookbook.github.io/2017/03/25/New-Study-Reveals-Lungs-Play-A-Key-Role-In-Blood-Production.html" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Alchemist Cookbook" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="New Study Reveals Lungs Play A Key Role In Blood Production" />
    <meta property="og:description" content="A new study completed by scientists from the University of San Francisco, published in Nature: International Weekly Journal of Science, on March 22, 2017 has, for the first time, directly identifed the lungs as a "primary site of terminal platelet production and an organ with considerable haematopoietic potential." Figure 1." />
    <meta property="og:url" content="https://alchemistcookbook.github.io/2017/03/25/New-Study-Reveals-Lungs-Play-A-Key-Role-In-Blood-Production.html" />
    <meta property="og:image" content="/images/lung-header.jpg" />
    <meta property="article:published_time" content="2017-03-25T00:00:00.000Z" />
    <meta property="article:tag" content="Health" />
    <meta property="article:tag" content="Biology" />
    <meta property="article:tag" content="Lungs" />
    <meta property="article:tag" content="Blood" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="New Study Reveals Lungs Play A Key Role In Blood Production" />
    <meta name="twitter:description" content="A new study completed by scientists from the University of San Francisco, published in Nature: International Weekly Journal of Science, on March 22, 2017 has, for the first time, directly identifed the lungs as a "primary site of terminal platelet production and an organ with considerable haematopoietic potential." Figure 1." />
    <meta name="twitter:url" content="https://alchemistcookbook.github.io/2017/03/25/New-Study-Reveals-Lungs-Play-A-Key-Role-In-Blood-Production.html" />
    <meta name="twitter:image:src" content="/images/lung-header.jpg" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Alchemist Cookbook" href="https://alchemistcookbook.github.io/rss/" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/styles/atom-one-dark.min.css">

        Alchemist Cookbook
        Extraordinary News & Information

New Study Reveals Lungs Play A Key Role In Blood Production

         <time class="timesince date" data-timesince="1490425200" datetime="2017-03-25T00:00" title="25 March 2017">2 days ago</time>
             Health, Biology, Lungs, Blood
             alchemistcookbook

A new study completed by scientists from the University of San Francisco, published in Nature: International Weekly Journal of Science, on March 22, 2017 has, for the first time, directly identifed the lungs as a "primary site of terminal platelet production and an organ with considerable haematopoietic potential."

Figure 1. The Pulmonary Curcuit

In a press release article by UCSF; Public Information Representative, Nicholas Weiler interviewed the study’s senior author, pulmonologist Mark R. Looney, MD, a professor of medicine and of laboratory medicine at UCSF.  He says, "This finding definitely suggests a more sophisticated view of the lungs – that they're not just for respiration but also a key partner in formation of crucial aspects of the blood. …What we've observed here in mice strongly suggests the lung may play a key role in blood formation in humans as well."

Also interviewed was Guadalupe Ortiz-Muñoz, co-first author of the study. Guadalupe says, "It’s possible that the lung is an ideal bioreactor for platelet production because of the mechanical force of the blood, or perhaps because of some molecular signaling we don’t yet know about."

Figure 2. Thoracic Anatomy

Here is a link to the study, published in Nature:

http://www.nature.com/nature/journal/vaop/ncurrent/full/nature21706.html

Here is a link to the press release by UCSF:

http://www.ucsf.edu/news/2017/03/406111/surprising-new-role-lungs-making-blood

Sources:

Title: The lung is a site of platelet biogenesis and a reservoir for haematopoietic progenitors
Author: Emma Lefrançais, Guadalupe Ortiz-Muñoz, Axelle Caudrillier, Beñat Mallavia, Fengchun Liu, David M. Sayah
Publication: Nature
Publisher: Nature Publishing Group
Date: Mar 22, 2017

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

Copyright © Alchemist Cookbook. All Rights Reserved.

            Built with  and Free and Open-Source Software.


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="general_lbl_font">20dp</dimen>
    <dimen name="general_sublbl_font">14dp</dimen>
    <dimen name="img_item_list">50dp</dimen>
    <dimen name="listtitle">16dp</dimen>
    <dimen name="listdescr">15dp</dimen>

</resources>


text:
package edu.umb.cs110.hw03.q01;

public class AlarmClock {
	// 1. Data Members
	private int currentTime;
	private int alarmTime;
	private boolean alarmState;
	// 2. Methods
	public void forwardTime(int seconds) {
		//If we insist on making it a real alarm clock
		//try {
		//    Thread.sleep(seconds * 1000);
		//} catch(InterruptedException ex) {
		//    Thread.currentThread().interrupt();
		//}
		this.currentTime += seconds;
		System.out.println("Current Time is "+ this.getCurrentTime());
	}
	public void reset() {
		this.currentTime = 0;
	}
	public void dismiss() {
		setAlarmState(false);
	}
	public void snoozeAlarm(int snoozeTime) {
		setAlarmTime(currentTime + snoozeTime);
	}
	public boolean isRinging() {
		return (this.alarmTime <= this.currentTime && this.getAlarmState()) ? true : false;
	}
	// 3. Getters and Setters
	public int getCurrentTime() {
		return currentTime;
	}
	public void setCurrentTime(int currentTime) {
		this.currentTime = currentTime;
	}
	public int getAlarmTime() {
		return alarmTime;
	}
	public void setAlarmTime(int alarmTime) {
		this.alarmTime = alarmTime;
	}
	public boolean getAlarmState() {
		return alarmState;
	}
	public void setAlarmState(boolean state) {
		this.alarmState = state;
	}
	// 4. Constructors
	public AlarmClock() {
		currentTime = 0;
		alarmTime = 0;
		alarmState = false;
	}
}


text:
case "$optimize" in
'') optimize="-O1" ;;
esac
d_setregid='undef'
d_setreuid='undef'
case "$usemymalloc" in
'') usemymalloc='y'
    ccflags="$ccflags -DNO_RCHECK"
    ;;
esac
# If somebody ignores the Cray PATH.
case ":$PATH:" in
*:/opt/ctl/bin:*) ;;
'') case "$cc" in
    '') test -x /opt/ctl/bin/cc && cc=/opt/ctl/bin/cc ;;
    esac
    ;;
esac
# As of UNICOS/mk 2.0.5.24 the shm* are in libc but unimplemented
# (an attempt to use them causes a runtime error)
# XXX Configure probe for really functional shm*() is needed XXX
if test "$d_shm" = ""; then
    d_shmat=${d_shmat:-undef}
    d_shmdt=${d_shmdt:-undef}
    d_shmget=${d_shmget:-undef}
    d_shmctl=${d_shmctl:-undef}
    case "$d_shmat$d_shmctl$d_shmdt$d_shmget" in
    *"undef"*) d_shm="$undef" ;;
    esac
fi
# Otherwise the unpack %65c checksums will fail.
pp_pack_cflags='optimize="-h scalar0 -h vector0"'
# No shared libraries.
so='none'
# Threads call-back unit.
cat > UU/usethreads.cbu <<'EOCBU'
# This script UU/usethreads.cbu will get 'called-back' by Configure
# after it has prompted the user for whether to use threads.
case "$usethreads" in
$define|true|[yY]*)
        set `echo X "$libswanted "| sed -e "s/ c / pthread c /"`
        shift
        libswanted="$*"
	;;
esac
EOCBU


text:
require "spec_helper"

describe Serializers::Import do
end


text:
class AddTimestamps < ActiveRecord::Migration[4.2]
  def change
    add_column :user_time_checks, :created_at, :datetime, null: false
    add_column :user_time_checks, :updated_at, :datetime, null: false

    add_column :user_leaves, :created_at, :datetime, null: false
    add_column :user_leaves, :updated_at, :datetime, null: false
  end
end


text:
class ChromeBrowserState;
@protocol SyncPresenter;

namespace web {
class WebState;
}

// Gets the top-level description message associated with the sync error state
// of |syncSetupService|. Returns nil if there is no sync error.
NSString* GetSyncErrorDescriptionForSyncSetupService(
    SyncSetupService* syncSetupService);

// Gets the string message associated with the sync error state of
// |browserState|. The returned error message does not contain any links.
// Returns nil if there is no sync error.
NSString* GetSyncErrorMessageForBrowserState(ChromeBrowserState* browserState);

// Gets the title of the button to fix the sync error of |browserState|.
// Returns nil if there is no sync error or it can't be fixed by a user action.
NSString* GetSyncErrorButtonTitleForBrowserState(
    ChromeBrowserState* browserState);

// Gets the sync state of |browserState|.
SyncSetupService::SyncServiceState GetSyncStateForBrowserState(
    ChromeBrowserState* browserState);

// Returns true if sync signin should be displayed based on |syncState|.
bool ShouldShowSyncSignin(SyncSetupService::SyncServiceState syncState);

// Returns true if sync passphrase settings should be displayed based on
// |syncState|.
bool ShouldShowSyncPassphraseSettings(
    SyncSetupService::SyncServiceState syncState);

// Returns true if Trusted Vault reauthentication dialog should be displayed
// based on |syncState|.
bool ShouldShowTrustedVaultReauthentication(
    SyncSetupService::SyncServiceState syncState);

// Returns true if sync settings (or the google services settings when unified
// consent is enabled) should be displayed based on |syncState|.
bool ShouldShowSyncSettings(SyncSetupService::SyncServiceState syncState);

// Check for sync errors, and display any that ought to be shown to the user.
// Returns true if an infobar was brought up.
bool DisplaySyncErrors(ChromeBrowserState* browser_state,
                       web::WebState* web_state,
                       id<SyncPresenter> presenter);

// Returns true if |errorState| corresponds to a transient sync error.
bool IsTransientSyncError(SyncSetupService::SyncServiceState errorState);

#endif  // IOS_CHROME_BROWSER_UI_SETTINGS_SYNC_UTILS_SYNC_UTIL_H_


text:
/*
 * File         : Struct.java
 * Author       : Aamir Shafi, Bryan Carpenter
 * Created      : Fri Sep 10 12:22:15 BST 2004
 * Revision     : $Revision: 1.16 $
 * Updated      : $Date: 2005/08/25 10:22:07 $
 */

package mpi;

import java.nio.ByteBuffer;

import mpjbuf.BufferFactory;
import mpjbuf.NIOBuffer;

/**
 * Subclass of `Datatype' representing a derived datatype created using
 * `Struct()'.
 * createWriteBuffer doesn't write the sectionHeader because Struct datatype
 * may consist of various different datatypes, thus the best place to write
 * these section headers (and read them as well) are pack() and unpack()
 * methods in StructPacker class. This behaviour is only exhibited,
 * (writing various different kind of sections) by Struct datatype.
 * Thus, it has be dealt here only. This
 * may not be the best way of doing this, but at the mom. it looks *the best*.
 */
public class Struct
    extends Datatype {

  private int[] blockLengths, displacements;
  private Datatype[] oldTypes;

  private boolean unitsOfOldExtent;
  // true => Indexed, false => Hindexed.

  private boolean unitBlocks;
  // Case where all blocks have unit length is detected and
  // treated specially.

  private Datatype oldType;
  private int numBlocks;
  //int extent = 0;

  /** you want to pack multiple type of non-contigous or contigous elements.
   */
  public Struct(int[] array_of_blocklengths, int[] array_of_displacements,
                Datatype[] array_of_types) throws MPIException {

    numBlocks = array_of_blocklengths.length;
    if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
      MPI.logger.debug("\n\n--struct--");
      MPI.logger.debug("numBlocks " + numBlocks);
    }

    blockLengths = new int[numBlocks];
    displacements = new int[numBlocks];
    oldTypes = new Datatype[numBlocks];
    if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
      MPI.logger.debug("iterating over numBlocks ");
    }

    for (int i = 0; i < numBlocks; i++) {
      blockLengths[i] = array_of_blocklengths[i];
      displacements[i] = array_of_displacements[i];
      oldTypes[i] = array_of_types[i];
      if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
        MPI.logger.debug("numBlocks[" + i + "] bkln<" + blockLengths[i] +
			">,dis<" +displacements[i] +
			">,otype<" + oldTypes[i] + ">");
      }
    }

    // Compute base type, type size
    baseType = UNDEFINED;
    for (int i = 0; i < numBlocks; i++) {
      Datatype oldType = oldTypes[i];
      int oldBaseType = oldType.baseType;
      if (oldBaseType != UNDEFINED) {
        if (baseType == UNDEFINED) {
          baseType = oldBaseType;
          bufferType = oldType.bufferType;
        }
        else if (oldBaseType != baseType) {
          /*MPIException.processMpiJavaException(MPI.ERR_TYPE,
                 "Base types of all component types in a Struct " +
                 "must agree.");*/
          throw new MPIException(
              "Base types of all component types in a Struct " +
              "must agree");
        }
        if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
          MPI.logger.debug("numBlocks[" + i + "] bkln<" + blockLengths[i] +
                        ">,dis<" + displacements[i] + ">,otype<" + oldTypes[i] +
                        ">");
	}
        size += blockLengths[i] * oldType.Size();
      }

      if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
        MPI.logger.debug("numBlocks[" + i + "] size<" + size + ">,otype<" +
                      oldTypes[i] + ">");
        MPI.logger.debug("baseType " + baseType);
      }
    }

    computeBounds();

    if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
      MPI.logger.debug("bufferType " + bufferType);
      MPI.logger.debug("after calling computeBounds");
      MPI.logger.debug("extent " + extent);
      MPI.logger.debug("lb " + lb);
      MPI.logger.debug("ub " + ub);
      MPI.logger.debug("lbSet " + lbSet);
      MPI.logger.debug("ubSet " + ubSet);
      MPI.logger.debug(
		      "bufferType for struct hasn't been set, "+
		      " and it won't work like this");
    }
  }

  private void computeBounds() throws MPIException {
    if(MPI.DEBUG && MPI.logger.isDebugEnabled())
      MPI.logger.debug("--computeBounds--");
    // Compute `ub' and `lb', which define the `extent' of the new type.
    // Also defines `ubSet', `lbSet' for this type.

    ubSet = false;
    lbSet = false;
    lb = Integer.MAX_VALUE;
    ub = Integer.MIN_VALUE;

    // Because currently we don't save the true lb (ub) of old types,
    // following will be an upper bound (lower bound), obtained
    // from precursor types for which lbSet (ubSet) is false.

    int trueLb = Integer.MAX_VALUE;
    int trueUb = Integer.MIN_VALUE;

    extent = 0; // Follow MPICH in defining extent to be zero if
    // bounds are undefined (i.e. empty type).

    if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
      MPI.logger.debug("initial values on computeBounds");
      MPI.logger.debug("extent " + extent);
      MPI.logger.debug("lb " + lb);
      MPI.logger.debug("ub " + ub);
      MPI.logger.debug("lbSet " + lbSet);
      MPI.logger.debug("ubSet " + ubSet);
      MPI.logger.debug("trueLb " + trueLb);
      MPI.logger.debug("trueUb " + trueUb);

      MPI.logger.debug("--iterating over the numBlocks<" + numBlocks);
    }
    for (int i = 0; i < numBlocks; i++) {
      int blockLen = blockLengths[i];

      if(MPI.DEBUG && MPI.logger.isDebugEnabled()) {
        MPI.logger.debug(" iteration<" + i + ">");
        MPI.logger.debug(" blklen <" + blockLen + ">");
      }

      if (blockLen < 0) {
        /*MPIException.processMpiJavaException(MPI.ERR_COUNT,
               "All block-lengths for Struct " +
               "must be non-negative.") ;*/
        throw new MPIException(
            "All block-lengths for Struct must be non-negative");
      }

      if (blockLen > 0) {
        if(MPI.DEBUG && MPI.logger.isDebugEnabled())
          MPI.logger.debug("if blklen > 0");
        Datatype oldtype = oldTypes[i];
        int oldBaseType = oldtype.baseType;
        if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
          MPI.logger.debug("getting old type" + oldtype);
          MPI.logger.debug("old base type" + oldBaseType);
	}
        int oldSize = oldtype.Size();
        if(MPI.DEBUG && MPI.logger.isDebugEnabled())
          MPI.logger.debug("old size " + oldSize);
        boolean oldUbSet = oldtype.ubSet;
        boolean oldLbSet = oldtype.lbSet;
        if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
          MPI.logger.debug("oldubset " + oldUbSet);
          MPI.logger.debug("oldlbset" + oldLbSet);
	}
        if (oldSize != 0 || oldLbSet || oldUbSet) {
          if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
            MPI.logger.debug("within oldSize != 0 or oldLbSet or oldUbSet ");
	  }
          // `oldtype.ub', `oldtype.lb', `oldtype.extent'
          // all well-defined.

          int oldExtent = oldtype.Extent();

          if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
            MPI.logger.debug("oldextent" + oldExtent);
	  }

          int max_ub = displacements[i] + (blockLen - 1) * oldExtent +
              oldtype.ub;
          if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
            MPI.logger.debug("max_ub" + max_ub);
	  }
          if (oldUbSet) {
            ubSet = true;
            if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
              MPI.logger.debug("(MPI.uB) max_ub" + max_ub);
              MPI.logger.debug("(MPI.uB) true" + trueUb);
              MPI.logger.debug("(MPI.uB) ub" + ub);
              MPI.logger.debug("(MPI.uB) oldtype.ub" + oldtype.ub);
	    }
            //aamir -- removed this if condition
            //if (max_ub > ub)
            ub = max_ub;

            if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
              MPI.logger.debug("(after((MPI.uB) ub" + ub);
	    }
          }
          else {
            if (max_ub > trueUb) {
              trueUb = max_ub;

              /* aamir (start) */
              if (max_ub > displacements[i])
                ub = max_ub; // + oldSize;
              else
                ub = displacements[i]; //+oldSize;

              //ub = (max_ub*displacements[i])+oldSize; //aamir + (what is epsolon here ??)
              //MPI.logger.debug("ub aamir ");
              /* aamir (end) */
            }
            /*
                else {
             ub = displacements[i] + oldSize;//aamir
                }*/
          }
          if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
            MPI.logger.debug("trueUb" + trueUb);
	  }
          int min_lb = displacements[i] + oldtype.lb;
          if (oldLbSet) {
            lbSet = true;
            if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
              MPI.logger.debug("(MPI.lB) min_lb" + min_lb);
              MPI.logger.debug("(MPI.lB) true" + trueLb);
              MPI.logger.debug("(MPI.lB) lb" + lb);
              MPI.logger.debug("(MPI.LB) oldtype.lb" + oldtype.lb);
	    }

            //aamir -- removed this if condition
            //if (min_lb < lb)
            lb = min_lb;

            if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
              MPI.logger.debug(")after((MPI.UB) lb" + lb);
	    }
          }
          else {
            if (min_lb < trueLb) {
              trueLb = min_lb;

              /* aamir (start) */
              if (min_lb < displacements[i])
                lb = min_lb;
              else
                lb = displacements[i];

              //lb = min_lb*displacements[i];
              //lb = min_lb;
              /* aamir (end) */
            }
            /*
                else
             lb = displacements[i];//aamir
             */
          }

          if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
            MPI.logger.debug("trueLb" + trueLb);
	  }
          /* Following "correct" according to standard, but likely to
             cause compatibility problems with MPICH?

                               int maxStartElement = startBlock +
                  oldExtent > 0 ? (blockLen - 1) * oldExtent : 0

                               // `ubSet' acts like a most significant positive bit in
                               // the maximization operation.

                               if (oldUbSet == ubSet) {
              int max_ub = maxStartElement + oldtype.ub ;
              if (max_ub > ub)
                  ub = max_ub ;
                               }
                               else if(oldUbSet) {
              ub    = maxStartElement + oldtype.ub ;
              ubSet = true ;
                               }

                               int minStartElement = startBlock +
                  oldExtent > 0 ? 0 : (blockLen - 1) * oldExtent ;

                               // `lbSet' acts like a most significant negative bit in
                               // the minimization operation.

                               if (oldLbSet == lbSet) {
              int min_lb = minStartElement + oldtype.lb ;
              if (min_lb < lb)
                  lb = min_lb ;
                               }
                               else if(oldLbSet) {
              lb    = minStartElement + oldtype.lb ;
              lbSet = true ;
                               }
           */
        }
      } //end if blkLen > 0

      if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
        MPI.logger.debug("lb<" + lb + ">");
        MPI.logger.debug("ub<" + ub + ">");
        MPI.logger.debug("trueLb<" + trueLb + ">");
        MPI.logger.debug("trueUb<" + trueUb + ">");
      }

    }

    if(MPI.DEBUG && MPI.logger.isDebugEnabled())  {
      MPI.logger.debug("(e)lb<" + lb + ">");
      MPI.logger.debug("(e)ub<" + ub + ">");
      MPI.logger.debug("(e)trueLb<" + trueLb + ">");
      MPI.logger.debug("(e)trueUb<" + trueUb + ">");
    }
    /*
           if(lb > trueLb) {

              // MPIException.processMpiJavaException(MPI.ERR_TYPE,
              //    "Compatibility restriction: in Struct, lb defined by MPI_LB " +
              //    "may not be higher than \"true\" lb.") ;

     throw new MPIException("Compatibility restriction");
           }

           if(ub < trueUb) {
              // MPIException.processMpiJavaException(MPI.ERR_TYPE,
              // "Compatibility restriction: in Struct, ub defined by MPI_UB " +
              // "may not be lower than \"true\" ub.") ;
       // throw new MPIException("Compatibility restriction");
           }
     */

    if (lb != Integer.MAX_VALUE || ub != Integer.MIN_VALUE)
      extent = ub - lb;
  }

  @Override
  public mpjbuf.Buffer createWriteBuffer(ByteBuffer slicedBuffer, int messageSize) {
    return new mpjbuf.Buffer( new NIOBuffer(messageSize, slicedBuffer),
		    MPI.BSEND_OVERHEAD , messageSize ) ;
  }

  @Override
  public mpjbuf.Buffer createWriteBuffer(int count) throws MPIException {
    int capacity = packedSize(count) +MPI.SEND_OVERHEAD ;
    int offset = MPI.SEND_OVERHEAD ;
    mpjbuf.RawBuffer rawBuffer = BufferFactory.create(capacity);
    mpjbuf.Buffer wBuffer = new mpjbuf.Buffer(rawBuffer, offset, capacity);

    try {
      wBuffer.putSectionHeader(this.bufferType);
    }
    catch (Exception e) {
      throw new MPIException(e);
    }

    return wBuffer;
  }

  @Override
mpjbuf.Buffer createReadBuffer(int count) {
    int capacity = packedSize(count)+ MPI.RECV_OVERHEAD ;
    int offset = MPI.RECV_OVERHEAD ;
    mpjbuf.RawBuffer rawBuffer = BufferFactory.create (capacity);
    mpjbuf.Buffer mpjbuf = new mpjbuf.Buffer( rawBuffer , offset, capacity) ;
    return mpjbuf;
  }

  @Override
int packedSize(int count) {
    /* calculate the size of each block, add them */
    int sectionHeader = 8; //what about multiple sections.

    for (int i = 0; i < blockLengths.length; i++) {
      int blockLen = blockLengths[i];
      Datatype oldtype = oldTypes[i];
      int sectionSize = 0;
      sectionSize = (blockLen * oldtype.byteSize);
   // int padding = 0;
   // if (sectionSize % 8 != 0)
   // padding = sectionSize % 8;
   // sectionSize += padding;
      byteSize += sectionSize;
    }

    /* calculate the size of each block, add them */
    return ((byteSize * count)+sectionHeader) ;
  }

  @Override
void setPacker() {
    packer = new StructPacker();
  }

  private class StructPacker
      extends GenericPacker {

    StructPacker() {
      super(Struct.this.extent, Struct.this.size); //what is size ?
    }

    public void pack(mpjbuf.Buffer mpjbuf, Object buf,
		    int offset) throws MPIException {

      int numBlocks = displacements.length;

      for (int i = 0; i < numBlocks; i++) {
        int boffset = offset + displacements[i];
        int blockLen = blockLengths[i];
        Datatype oldtype = oldTypes[i];
        Packer itemPacker = oldtype.getPacker();
        int itemExtent = oldtype.extent;
        for (int j = 0; j < blockLen; j++) {
          itemPacker.pack(mpjbuf, buf, boffset);
          boffset += itemExtent;
        }
      }
    }

    public void unpack(mpjbuf.Buffer mpjbuf, Object buf,
		    int offset) throws MPIException {

      int numBlocks = displacements.length;

      for (int i = 0; i < numBlocks; i++) {
        int boffset = offset + displacements[i];
        int blockLen = blockLengths[i];
        Datatype oldtype = oldTypes[i];

        Packer itemPacker = oldtype.getPacker();
        int itemExtent = oldtype.extent;

        for (int j = 0; j < blockLen; j++) {
          itemPacker.unpack(mpjbuf, buf, boffset, itemExtent);
          boffset += itemExtent;
        }

        if (oldtype.bufferType == null)
          System.out.println("bufferType is null in createWriteBuffer");
      }
    }

    public void unpackPartial(mpjbuf.Buffer mpjbuf, int length,
                              Object buf, int offset) throws MPIException {

      int numBlocks = displacements.length;
      int residue = length;
      int boffset = 0;
      Datatype oldtype = null;
      //Packer itemPacker;

      for (int i = 0; i < numBlocks; i++) {
        boffset = offset + displacements[i];
        int blockLen = blockLengths[i];
        oldtype = oldTypes[i];

        int blockSize = blockLen * oldtype.size;

        if (residue < blockSize)break;

        Packer itemPacker = oldtype.getPacker(); //just to avoid errors
        int itemLen = oldtype.extent;

        for (int j = 0; j < blockLen; j++) {
          itemPacker.unpack(mpjbuf, buf, boffset);
          boffset += itemLen;
        }

        residue -= blockSize;
      }

      // Precondition is `length < size'.
      // So `size > 0'.  So `numBlocks > 0'.
      // So `boffset', `oldtype' always defined on exit from above loop.

      int remFull = residue / oldtype.size;
      for (int j = 0; j < remFull; j++) {
        //is this itemPacker good enough here ?

        Packer itemPacker = oldtype.getPacker(); //just to avoid errors
        int itemLen = oldtype.extent;
        itemPacker.unpack(mpjbuf, buf, boffset);
        boffset += itemLen;
      }

      residue -= remFull * oldtype.size;
      Packer itemPacker = oldtype.getPacker(); //jsut to avoid errors
      if (residue > 0)
        itemPacker.unpackPartial(mpjbuf, residue, buf, boffset);
    }
  }

}

// Things to do:
//


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package obj;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author ASUS TRONY
 */
public class Professore {
    private int id ;
    private String nome ;
    private String cognome;
    private String data ="";

    public Professore() {
    }

    public Professore(int id, String nome, String cognome, String data) {
        this.id = id;
        this.nome = nome;
        this.cognome = cognome;
        this.data = data;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getCognome() {
        return cognome;
    }

    public void setCognome(String cognome) {
        this.cognome = cognome;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public void save(){
    //controlla se esiste , modifica o crea;
    }

    public void Load(int i) throws SQLException{
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/MYUNIVAQ?zeroDateTimeBehavior=convertToNull","root","mysql");
        Statement stmt = null;
    String query = "select * " +
                   "from  MYUNIVAQ.Professore "+
                    "WHERE Professore.id =" +i ;
    try {
        stmt = con.createStatement();
            try (ResultSet rs = stmt.executeQuery(query)) {
                while (rs.next()) {

                    this.data = rs.getString("dataDiNascita");
                    this.id = rs.getInt("id");
                    this.nome = rs.getString("nome");
                    this.cognome = rs.getString("cognome");

                }
            }
    }catch (SQLException e ) {

    } finally {
         con.close();
        if (stmt != null) { stmt.close(); }
    }

    }
}