public ExtantNetwork extantNetwork()
     throws NotEnoughResourcesException, TransientEntityException {
   if (!NetworkGroups.networkingConfiguration().hasNetworking()) {
     ExtantNetwork bogusNet = ExtantNetwork.bogus(this);
     if (!this.hasExtantNetwork()) this.setExtantNetwork(bogusNet);
     return bogusNet;
   } else if (!Entities.isPersistent(this)) {
     throw new TransientEntityException(this.toString());
   } else {
     ExtantNetwork exNet = this.getExtantNetwork();
     if (exNet == null) {
       for (Integer i : Numbers.shuffled(NetworkGroups.networkTagInterval())) {
         try {
           Entities.uniqueResult(ExtantNetwork.named(i));
           continue;
         } catch (Exception ex) {
           exNet = ExtantNetwork.create(this, i);
           Entities.persist(exNet);
           this.setExtantNetwork(exNet);
           return this.getExtantNetwork();
         }
       }
       throw new NotEnoughResourcesException(
           "Failed to allocate network tag for network: "
               + this.getFullName()
               + ": no network tags are free.");
     } else {
       return this.getExtantNetwork();
     }
   }
 }
    @Override
    public boolean apply(Allocation allocInfo) throws MetadataException {
      Context ctx = allocInfo.getContext();
      NetworkGroups.lookup(
          ctx.getUserFullName().asAccountFullName(), NetworkGroups.defaultNetworkName());

      Set<String> networkNames = Sets.newHashSet(allocInfo.getRequest().getGroupSet());
      if (networkNames.isEmpty()) {
        networkNames.add(NetworkGroups.defaultNetworkName());
      }

      Map<String, NetworkGroup> networkRuleGroups = Maps.newHashMap();
      for (String groupName : networkNames) {
        NetworkGroup group =
            NetworkGroups.lookup(ctx.getUserFullName().asAccountFullName(), groupName);
        if (!ctx.hasAdministrativePrivileges()
            && !RestrictedTypes.filterPrivileged().apply(group)) {
          throw new IllegalMetadataAccessException(
              "Not authorized to use network group "
                  + groupName
                  + " for "
                  + ctx.getUser().getName());
        }
        networkRuleGroups.put(groupName, group);
      }
      Set<String> missingNets = Sets.difference(networkNames, networkRuleGroups.keySet());
      if (!missingNets.isEmpty()) {
        throw new NoSuchMetadataException("Failed to find security group info for: " + missingNets);
      } else {
        allocInfo.setNetworkRules(networkRuleGroups);
      }
      return true;
    }
 public static List<Integer> networkTagInterval() {
   final List<Integer> interval = Lists.newArrayList();
   for (Integer i = NetworkGroups.networkingConfiguration().getMinNetworkTag();
       i < NetworkGroups.networkingConfiguration().getMaxNetworkTag();
       i++) {
     interval.add(i);
   }
   return interval;
 }
 public static List<Long> networkIndexInterval() {
   final List<Long> interval = Lists.newArrayList();
   for (Long i = NetworkGroups.networkingConfiguration().getMinNetworkIndex();
       i < NetworkGroups.networkingConfiguration().getMaxNetworkIndex();
       i++) {
     interval.add(i);
   }
   return interval;
 }
 public ExtantNetwork reclaim(Integer i)
     throws NotEnoughResourcesException, TransientEntityException {
   if (!NetworkGroups.networkingConfiguration().hasNetworking()) {
     return ExtantNetwork.bogus(this);
   } else if (!Entities.isPersistent(this)) {
     throw new TransientEntityException(this.toString());
   } else {
     ExtantNetwork exNet = Entities.persist(ExtantNetwork.create(this, i));
     this.setExtantNetwork(exNet);
     return this.getExtantNetwork();
   }
 }
 /**
  * Resolve Group Names / Identifiers for the given permissions.
  *
  * <p>Caller must have open transaction.
  *
  * @param permissions - The permissions to update
  * @throws MetadataException If an error occurs
  */
 public static void resolvePermissions(final Iterable<IpPermissionType> permissions)
     throws MetadataException {
   for (final IpPermissionType ipPermission : permissions) {
     if (ipPermission.getGroups() != null)
       for (final UserIdGroupPairType groupInfo : ipPermission.getGroups()) {
         if (!Strings.isNullOrEmpty(groupInfo.getSourceGroupId())) {
           final NetworkGroup networkGroup =
               NetworkGroups.lookupByGroupId(groupInfo.getSourceGroupId());
           groupInfo.setSourceUserId(networkGroup.getOwnerAccountNumber());
           groupInfo.setSourceGroupName(networkGroup.getDisplayName());
         } else if (Strings.isNullOrEmpty(groupInfo.getSourceUserId())
             || Strings.isNullOrEmpty(groupInfo.getSourceGroupName())) {
           throw new MetadataException("Group ID or User ID/Group Name required.");
         } else {
           final NetworkGroup networkGroup =
               NetworkGroups.lookup(
                   AccountFullName.getInstance(groupInfo.getSourceUserId()),
                   groupInfo.getSourceGroupName());
           groupInfo.setSourceGroupId(networkGroup.getGroupId());
         }
       }
   }
 }
 /**
  * Update network tag information by marking reported tags as being EXTANT and removing previously
  * EXTANT tags which are no longer reported
  *
  * @param activeNetworks
  */
 public static void updateExtantNetworks(
     ServiceConfiguration cluster, List<NetworkInfoType> activeNetworks) {
   ActiveTags.INSTANCE.update(cluster, activeNetworks);
   /**
    * For each of the reported active network tags ensure that the locally stored extant network
    * state reflects that the network has now been EXTANT in the system (i.e. is no longer PENDING)
    */
   for (NetworkInfoType activeNetInfo : activeNetworks) {
     EntityTransaction tx = Entities.get(NetworkGroup.class);
     try {
       NetworkGroup net = NetworkGroups.lookupByNaturalId(activeNetInfo.getUuid());
       if (net.hasExtantNetwork()) {
         ExtantNetwork exNet = net.extantNetwork();
         if (Reference.State.PENDING.equals(exNet.getState())) {
           LOG.debug(
               "Found PENDING extant network for " + net.getFullName() + " updating to EXTANT.");
           exNet.setState(Reference.State.EXTANT);
         } else {
           LOG.debug(
               "Found "
                   + exNet.getState()
                   + " extant network for "
                   + net.getFullName()
                   + ": skipped.");
         }
       } else {
         LOG.warn(
             "Failed to find extant network for "
                 + net.getFullName()); // TODO:GRZE: likely we should be trying to reclaim tag here
       }
       tx.commit();
     } catch (Exception ex) {
       LOG.debug(ex);
       Logs.extreme().error(ex, ex);
     } finally {
       if (tx.isActive()) tx.rollback();
     }
   }
   /**
    * For each defined network group check to see if the extant network is in the set of active
    * tags and remove it if appropriate.
    *
    * <p>It is appropriate to remove the network when the state of the extant network is {@link
    * Reference.State.RELEASING}.
    *
    * <p>Otherwise, if {@link ActiveTags#INSTANCE#isActive()} is false and:
    *
    * <ol>
    *   <li>The state of the extant network is {@link Reference.State.EXTANT}
    *   <li>The state of the extant network is {@link Reference.State.PENDING} and has exceeded
    *       {@link NetworksGroups#NETWORK_TAG_PENDING_TIMEOUT}
    * </ol>
    *
    * Then the state of the extant network is updated to {@link Reference.State.RELEASING}.
    */
   try {
     final List<NetworkGroup> groups = NetworkGroups.lookupAll(null, null);
     for (NetworkGroup net : groups) {
       final EntityTransaction tx = Entities.get(NetworkGroup.class);
       try {
         net = Entities.merge(net);
         if (net.hasExtantNetwork()) {
           ExtantNetwork exNet = net.getExtantNetwork();
           Integer exNetTag = exNet.getTag();
           if (!ActiveTags.INSTANCE.isActive(exNetTag)) {
             if (Reference.State.EXTANT.equals(exNet.getState())) {
               exNet.setState(Reference.State.RELEASING);
             } else if (Reference.State.PENDING.equals(exNet.getState())
                 && exNet.lastUpdateMillis()
                     > 60L * 1000 * NetworkGroups.NETWORK_TAG_PENDING_TIMEOUT) {
               exNet.setState(Reference.State.RELEASING);
             } else if (Reference.State.RELEASING.equals(exNet.getState())) {
               exNet.teardown();
               Entities.delete(exNet);
               net.setExtantNetwork(null);
             }
           }
         }
         tx.commit();
       } catch (final Exception ex) {
         LOG.debug(ex);
         Logs.extreme().error(ex, ex);
       } finally {
         if (tx.isActive()) tx.rollback();
       }
     }
   } catch (MetadataException ex) {
     LOG.error(ex);
   }
 }