Example usage for com.google.common.base Functions forPredicate

List of usage examples for com.google.common.base Functions forPredicate

Introduction

In this page you can find the example usage for com.google.common.base Functions forPredicate.

Prototype

public static <T> Function<T, Boolean> forPredicate(Predicate<T> predicate) 

Source Link

Document

Creates a function that returns the same boolean output as the given predicate for all inputs.

Usage

From source file:brooklyn.entity.webapp.tomcat.TomcatServerImpl.java

@Override
public void connectSensors() {
    super.connectSensors();

    if (getDriver().isJmxEnabled()) {
        String requestProcessorMbeanName = "Catalina:type=GlobalRequestProcessor,name=\"http-*\"";

        Integer port = isHttpsEnabled() ? getAttribute(HTTPS_PORT) : getAttribute(HTTP_PORT);
        String connectorMbeanName = format("Catalina:type=Connector,port=%s", port);

        jmxWebFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
                .pollAttribute(new JmxAttributePollConfig<Integer>(ERROR_COUNT)
                        .objectName(requestProcessorMbeanName).attributeName("errorCount"))
                .pollAttribute(new JmxAttributePollConfig<Integer>(REQUEST_COUNT)
                        .objectName(requestProcessorMbeanName).attributeName("requestCount"))
                .pollAttribute(new JmxAttributePollConfig<Integer>(TOTAL_PROCESSING_TIME)
                        .objectName(requestProcessorMbeanName).attributeName("processingTime"))
                .pollAttribute(new JmxAttributePollConfig<String>(CONNECTOR_STATUS)
                        .objectName(connectorMbeanName).attributeName("stateName"))
                .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_PROCESS_IS_RUNNING)
                        .objectName(connectorMbeanName).attributeName("stateName")
                        .onSuccess(Functions.forPredicate(Predicates.<Object>equalTo("STARTED")))
                        .setOnFailureOrException(false))
                .build();/* w  w w .ja  v  a 2s .  c o  m*/

        jmxAppFeed = JavaAppUtils.connectMXBeanSensors(this);
    } else {
        // if not using JMX
        LOG.warn("Tomcat running without JMX monitoring; limited visibility of service available");
        connectServiceUpIsRunning();
    }
}

From source file:brooklyn.entity.messaging.activemq.ActiveMQBrokerImpl.java

@Override
protected void connectSensors() {
    setAttribute(BROKER_URL,//from  w  ww  . j ava  2 s.  co  m
            String.format("tcp://%s:%d", getAttribute(HOSTNAME), getAttribute(OPEN_WIRE_PORT)));

    String brokerMbeanName = "org.apache.activemq:type=Broker,brokerName=" + getBrokerName();

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(brokerMbeanName)
                    .attributeName("BrokerName").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onFailureOrException(Functions.constant(false)))
            .build();
}

From source file:org.apache.brooklyn.entity.messaging.activemq.ActiveMQBrokerImpl.java

@Override
protected void connectSensors() {
    sensors().set(BROKER_URL,//ww  w. j a v  a  2 s. c  om
            String.format("tcp://%s:%d", getAttribute(HOSTNAME), getAttribute(OPEN_WIRE_PORT)));

    String brokerMbeanName = "org.apache.activemq:type=Broker,brokerName=" + getBrokerName();

    jmxFeed = JmxFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP).objectName(brokerMbeanName)
                    .attributeName("BrokerName").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onFailureOrException(Functions.constant(false)).suppressDuplicates(true))
            .build();
}

From source file:com.eucalyptus.component.groups.ServiceGroup.java

public Supplier<Map<ComponentId, Boolean>> groupMemberSupplier() {
    return new Supplier<Map<ComponentId, Boolean>>() {
        @Override/* w w w .j a  v a  2s  . c om*/
        public Map<ComponentId, Boolean> get() {
            return Maps.asMap(Sets.newHashSet(ComponentIds.list()), Functions.forPredicate(ServiceGroup.this));
        }
    };
}

From source file:com.google.auto.factory.processor.FactoryDescriptorGenerator.java

FactoryMethodDescriptor generateDescriptorForConstructor(final AutoFactoryDeclaration declaration,
        ExecutableElement constructor) {
    checkNotNull(constructor);//w  w w .ja v  a  2 s.  c om
    checkArgument(constructor.getKind() == ElementKind.CONSTRUCTOR);
    Element classElement = constructor.getEnclosingElement();
    Name returnType = classElement.accept(new ElementKindVisitor6<Name, Void>() {
        @Override
        protected Name defaultAction(Element e, Void p) {
            throw new AssertionError();
        }

        @Override
        public Name visitTypeAsClass(TypeElement e, Void p) {
            if (!e.getTypeParameters().isEmpty()) {
                messager.printMessage(ERROR, "AutoFactory does not support generic types", e);
            }
            return e.getQualifiedName();
        }
    }, null);
    ImmutableListMultimap<Boolean, ? extends VariableElement> parameterMap = Multimaps
            .index(constructor.getParameters(), Functions.forPredicate(new Predicate<VariableElement>() {
                @Override
                public boolean apply(VariableElement parameter) {
                    return parameter.getAnnotation(Provided.class) != null;
                }
            }));
    ImmutableSet<Parameter> providedParameters = Parameter.forParameterList(parameterMap.get(true));
    ImmutableSet<Parameter> passedParameters = Parameter.forParameterList(parameterMap.get(false));
    return new FactoryMethodDescriptor.Builder(declaration)
            .factoryName(declaration.getFactoryName(elements.getPackageOf(constructor).getQualifiedName(),
                    classElement.getSimpleName()))
            .name("create").returnType(returnType.toString())
            .publicMethod(constructor.getEnclosingElement().getModifiers().contains(PUBLIC))
            .providedParameters(providedParameters).passedParameters(passedParameters)
            .creationParameters(Parameter.forParameterList(constructor.getParameters())).build();
}

From source file:com.eucalyptus.cluster.callback.VmRunCallback.java

@Override
public void fireException(final Throwable e) {
    LOG.debug(LogUtil.header("Failing run instances because of: " + e.getMessage()), e);
    LOG.debug(LogUtil.subheader(VmRunCallback.this.getRequest().toString()));
    Predicate<Throwable> rollbackToken = new Predicate<Throwable>() {

        @Override/* w  ww.  j av  a 2s  . com*/
        public boolean apply(Throwable input) {
            LOG.debug("-> Release resource tokens for unused resources.");
            try {
                VmRunCallback.this.token.abort();
            } catch (final Exception ex) {
                LOG.error(ex.getMessage());
                Logs.extreme().error(ex, ex);
            }
            return true;
        }
    };
    try {
        Entities.asTransaction(VmInstance.class, Functions.forPredicate(rollbackToken)).apply(e);
    } catch (Exception ex) {
        Logs.extreme().error(ex, ex);
    }
}

From source file:brooklyn.entity.nosql.cassandra.CassandraNodeImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//w  w  w.  j  a  v  a 2s. c  om
protected void connectSensors() {
    // "cassandra" isn't really a protocol, but okay for now
    setAttribute(DATASTORE_URL, "cassandra://" + getAttribute(HOSTNAME) + ":" + getAttribute(THRIFT_PORT));

    super.connectSensors();

    jmxHelper = new JmxHelper(this);
    jmxFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).helper(jmxHelper)
            .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP_JMX).objectName(storageServiceMBean)
                    .attributeName("Initialized").onSuccess(Functions.forPredicate(Predicates.notNull()))
                    .onException(Functions.constant(false)))
            .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Set<BigInteger>>() {
                        @Override
                        public Set<BigInteger> apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            if (input == null || input.isEmpty())
                                return null;
                            // FIXME does not work on aws-ec2, uses RFC1918 address
                            Predicate<String> self = Predicates
                                    .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                            getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                            Set<String> tokens = Maps.filterValues(input, self).keySet();
                            Set<BigInteger> result = Sets.newLinkedHashSet();
                            for (String token : tokens) {
                                result.add(new BigInteger(token));
                            }
                            return result;
                        }
                    }).onException(Functions.<Set<BigInteger>>constant(null)))
            .pollAttribute(new JmxAttributePollConfig<BigInteger>(TOKEN).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, BigInteger>() {
                        @Override
                        public BigInteger apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            // TODO remove duplication from setting TOKENS
                            if (input == null || input.isEmpty())
                                return null;
                            // FIXME does not work on aws-ec2, uses RFC1918 address
                            Predicate<String> self = Predicates
                                    .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                            getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                            Set<String> tokens = Maps.filterValues(input, self).keySet();
                            String token = Iterables.getFirst(tokens, null);
                            return (token != null) ? new BigInteger(token) : null;
                        }
                    }).onException(Functions.<BigInteger>constant(null)))
            .pollOperation(new JmxOperationPollConfig<String>(DATACENTER_NAME).period(60, TimeUnit.SECONDS)
                    .objectName(snitchMBean).operationName("getDatacenter")
                    .operationParams(ImmutableList.of(getBroadcastAddress()))
                    .onException(Functions.<String>constant(null)))
            .pollOperation(new JmxOperationPollConfig<String>(RACK_NAME).period(60, TimeUnit.SECONDS)
                    .objectName(snitchMBean).operationName("getRack")
                    .operationParams(ImmutableList.of(getBroadcastAddress()))
                    .onException(Functions.<String>constant(null)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS).objectName(storageServiceMBean)
                    .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@Nullable Object arg) {
                            Map input = (Map) arg;
                            if (input == null || input.isEmpty())
                                return 0;
                            return input.size();
                        }
                    }).onException(Functions.constant(-1)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT).objectName(storageServiceMBean)
                    .attributeName("LiveNodes").onSuccess(new Function<Object, Integer>() {
                        @Override
                        public Integer apply(@Nullable Object arg) {
                            List input = (List) arg;
                            if (input == null || input.isEmpty())
                                return 0;
                            return input.size();
                        }
                    }).onException(Functions.constant(-1)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(READ_ACTIVE).objectName(readStageMBean)
                    .attributeName("ActiveCount").onException(Functions.constant((Integer) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(READ_PENDING).objectName(readStageMBean)
                    .attributeName("PendingTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(READ_COMPLETED).objectName(readStageMBean)
                    .attributeName("CompletedTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Integer>(WRITE_ACTIVE).objectName(mutationStageMBean)
                    .attributeName("ActiveCount").onException(Functions.constant((Integer) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_PENDING).objectName(mutationStageMBean)
                    .attributeName("PendingTasks").onException(Functions.constant((Long) null)))
            .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_COMPLETED).objectName(mutationStageMBean)
                    .attributeName("CompletedTasks").onException(Functions.constant((Long) null)))
            .build();

    functionFeed = FunctionFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
            .poll(new FunctionPollConfig<Long, Long>(THRIFT_PORT_LATENCY)
                    .onException(Functions.constant((Long) null)).callable(new Callable<Long>() {
                        public Long call() {
                            try {
                                long start = System.currentTimeMillis();
                                Socket s = new Socket(getAttribute(Attributes.HOSTNAME), getThriftPort());
                                s.close();
                                long latency = System.currentTimeMillis() - start;
                                computeServiceUp();
                                return latency;
                            } catch (Exception e) {
                                if (log.isDebugEnabled())
                                    log.debug("Cassandra thrift port poll failure: " + e);
                                setAttribute(SERVICE_UP, false);
                                return null;
                            }
                        }

                        public void computeServiceUp() {
                            // this will wait an additional poll period after thrift port is up,
                            // as the caller will not have set yet, but that will help ensure it is really healthy!
                            setAttribute(SERVICE_UP,
                                    getAttribute(THRIFT_PORT_LATENCY) != null
                                            && getAttribute(THRIFT_PORT_LATENCY) >= 0
                                            && Boolean.TRUE.equals(getAttribute(SERVICE_UP_JMX)));
                        }
                    }))
            .build();

    jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this);
}

From source file:org.apache.brooklyn.entity.nosql.cassandra.CassandraNodeImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from   w w w .jav  a  2s .  co  m*/
protected void connectSensors() {
    // "cassandra" isn't really a protocol, but okay for now
    sensors().set(DATASTORE_URL, "cassandra://" + getAttribute(HOSTNAME) + ":" + getAttribute(THRIFT_PORT));

    super.connectSensors();

    jmxHelper = new JmxHelper(this);
    boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

    if (getDriver().isJmxEnabled()) {
        jmxFeed = JmxFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).helper(jmxHelper)
                .pollAttribute(new JmxAttributePollConfig<Boolean>(SERVICE_UP_JMX)
                        .objectName(storageServiceMBean).attributeName("Initialized")
                        .onSuccess(Functions.forPredicate(Predicates.notNull()))
                        .onException(Functions.constant(false)).suppressDuplicates(true))
                .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS)
                        .objectName(storageServiceMBean).attributeName("TokenToEndpointMap")
                        .onSuccess(new Function<Object, Set<BigInteger>>() {
                            @Override
                            public Set<BigInteger> apply(@Nullable Object arg) {
                                Map input = (Map) arg;
                                if (input == null || input.isEmpty())
                                    return null;
                                // FIXME does not work on aws-ec2, uses RFC1918 address
                                Predicate<String> self = Predicates
                                        .in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS),
                                                getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
                                Set<String> tokens = Maps.filterValues(input, self).keySet();
                                Set<BigInteger> result = Sets.newLinkedHashSet();
                                for (String token : tokens) {
                                    result.add(new BigInteger(token));
                                }
                                return result;
                            }
                        }).onException(Functions.<Set<BigInteger>>constant(null)).suppressDuplicates(true))
                .pollOperation(new JmxOperationPollConfig<String>(DATACENTER_NAME).period(60, TimeUnit.SECONDS)
                        .objectName(snitchMBean).operationName("getDatacenter")
                        .operationParams(ImmutableList.of(getBroadcastAddress()))
                        .onException(Functions.<String>constant(null)).suppressDuplicates(true))
                .pollOperation(new JmxOperationPollConfig<String>(RACK_NAME).period(60, TimeUnit.SECONDS)
                        .objectName(snitchMBean).operationName("getRack")
                        .operationParams(ImmutableList.of(getBroadcastAddress()))
                        .onException(Functions.<String>constant(null)).suppressDuplicates(true))
                .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS).objectName(storageServiceMBean)
                        .attributeName("TokenToEndpointMap").onSuccess(new Function<Object, Integer>() {
                            @Override
                            public Integer apply(@Nullable Object arg) {
                                Map input = (Map) arg;
                                if (input == null || input.isEmpty())
                                    return 0;
                                return input.size();
                            }
                        }).onException(Functions.constant(-1)))
                .pollAttribute(
                        new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT).objectName(storageServiceMBean)
                                .attributeName("LiveNodes").onSuccess(new Function<Object, Integer>() {
                                    @Override
                                    public Integer apply(@Nullable Object arg) {
                                        List input = (List) arg;
                                        if (input == null || input.isEmpty())
                                            return 0;
                                        return input.size();
                                    }
                                }).onException(Functions.constant(-1)))
                .pollAttribute(new JmxAttributePollConfig<Integer>(READ_ACTIVE).objectName(readStageMBean)
                        .attributeName("ActiveCount").onException(Functions.constant((Integer) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(READ_PENDING).objectName(readStageMBean)
                        .attributeName("PendingTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(READ_COMPLETED).objectName(readStageMBean)
                        .attributeName("CompletedTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Integer>(WRITE_ACTIVE).objectName(mutationStageMBean)
                        .attributeName("ActiveCount").onException(Functions.constant((Integer) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_PENDING).objectName(mutationStageMBean)
                        .attributeName("PendingTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .pollAttribute(new JmxAttributePollConfig<Long>(WRITE_COMPLETED).objectName(mutationStageMBean)
                        .attributeName("CompletedTasks").onException(Functions.constant((Long) null))
                        .enabled(retrieveUsageMetrics))
                .build();

        jmxMxBeanFeed = JavaAppUtils.connectMXBeanSensors(this);
    }

    if (Boolean.TRUE.equals(getConfig(USE_THRIFT_MONITORING))) {
        functionFeed = FunctionFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS)
                .poll(new FunctionPollConfig<Long, Long>(THRIFT_PORT_LATENCY)
                        .onException(Functions.constant(-1L))
                        .callable(new ThriftLatencyChecker(CassandraNodeImpl.this))
                        .enabled(retrieveUsageMetrics))
                .build();
    }

    connectServiceUpIsRunning();
}

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public CreateDhcpOptionsResponseType createDhcpOptions(final CreateDhcpOptionsType request)
        throws EucalyptusCloudException {
    final CreateDhcpOptionsResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final Supplier<DhcpOptionSet> allocator = new Supplier<DhcpOptionSet>() {
        @Override/*  w  w w . j  a va 2s  . co  m*/
        public DhcpOptionSet get() {
            try {
                final DhcpOptionSet dhcpOptionSet = DhcpOptionSet.create(ctx.getUserFullName(),
                        Identifier.dopt.generate());
                for (final DhcpConfigurationItemType item : request.getDhcpConfigurationSet().getItem()) {
                    final List<String> values = item.values();
                    boolean validValue = false;
                    out: switch (item.getKey()) {
                    case DhcpOptionSets.DHCP_OPTION_DOMAIN_NAME:
                        validValue = values.size() == 1 && InternetDomainName.isValid(values.get(0));
                        break;
                    case DhcpOptionSets.DHCP_OPTION_DOMAIN_NAME_SERVERS:
                        validValue = values.size() == 1 && "AmazonProvidedDNS".equals(values.get(0));
                        if (validValue)
                            break; // else fallthrough
                    case DhcpOptionSets.DHCP_OPTION_NTP_SERVERS: // fallthrough
                    case DhcpOptionSets.DHCP_OPTION_NETBIOS_NAME_SERVERS:
                        for (final String value : values) {
                            validValue = InetAddresses.isInetAddress(value);
                            if (!validValue)
                                break out;
                        }
                        break;
                    case DhcpOptionSets.DHCP_OPTION_NETBIOS_NODE_TYPE:
                        validValue = values.size() == 1 && Optional.fromNullable(Ints.tryParse(values.get(0)))
                                .transform(
                                        Functions.forPredicate(Predicates.in(Lists.newArrayList(1, 2, 4, 8))))
                                .or(false);
                        break;
                    default:
                        throw new ClientComputeException("InvalidParameterValue", "Value (" + item.getKey()
                                + ") for parameter name is invalid. Unknown DHCP option");
                    }
                    if (!validValue || values.isEmpty()) {
                        throw new ClientComputeException("InvalidParameterValue",
                                "Value (" + Joiner.on(',').join(values)
                                        + ") for parameter value is invalid. Invalid DHCP option value.");
                    }
                    dhcpOptionSet.getDhcpOptions()
                            .add(DhcpOption.create(dhcpOptionSet, item.getKey(), item.values()));
                }
                return dhcpOptionSets.save(dhcpOptionSet);
            } catch (Exception ex) {
                throw Exceptions.toUndeclared(ex);
            }
        }
    };
    reply.setDhcpOptions(allocate(allocator, DhcpOptionSet.class, DhcpOptionsType.class));
    return reply;
}

From source file:com.eucalyptus.compute.vpc.VpcManager.java

public CreateVpcResponseType createVpc(final CreateVpcType request) throws EucalyptusCloudException {
    final CreateVpcResponseType reply = request.getReply();
    final Context ctx = Contexts.lookup();
    final UserFullName userFullName = ctx.getUserFullName();
    final boolean createDefault = ctx.isAdministrator() && request.getCidrBlock().matches("[0-9]{12}");
    if (!Cidr.parse().apply(request.getCidrBlock()).transform(Cidr.prefix())
            .transform(Functions.forPredicate(Range.closed(16, 28))).or(createDefault)) {
        throw new ClientComputeException("InvalidVpcRange", "Cidr range invalid: " + request.getCidrBlock());
    }/*from   w  ww  .  j a va  2  s .co m*/
    final Supplier<Vpc> allocator = new Supplier<Vpc>() {
        @Override
        public Vpc get() {
            try {
                final String vpcCidr;
                final AccountFullName vpcAccountFullName;
                final UserFullName vpcOwnerFullName;
                Vpc vpc = null;
                RouteTable routeTable = null;
                NetworkAcl networkAcl = null;
                if (createDefault) {
                    final UserPrincipal user = Accounts.lookupPrincipalByAccountNumber(request.getCidrBlock());
                    vpcCidr = Vpcs.DEFAULT_VPC_CIDR;
                    vpcAccountFullName = AccountFullName.getInstance(user.getAccountNumber());
                    vpcOwnerFullName = UserFullName.getInstance(user);

                    // check for existing vpc
                    try {
                        vpc = vpcs.lookupDefault(vpcAccountFullName, Functions.<Vpc>identity());
                        routeTable = routeTables.lookupMain(vpc.getDisplayName(),
                                Functions.<RouteTable>identity());
                        networkAcl = networkAcls.lookupDefault(vpc.getDisplayName(),
                                Functions.<NetworkAcl>identity());
                    } catch (final VpcMetadataNotFoundException e) {
                        // so create it
                    }
                } else {
                    vpcCidr = request.getCidrBlock();
                    vpcAccountFullName = userFullName.asAccountFullName();
                    vpcOwnerFullName = userFullName;
                }
                if (vpc == null) {
                    DhcpOptionSet options;
                    try {
                        options = dhcpOptionSets.lookupByExample(
                                DhcpOptionSet.exampleDefault(vpcAccountFullName), vpcAccountFullName, "default",
                                Predicates.alwaysTrue(), Functions.<DhcpOptionSet>identity());
                    } catch (VpcMetadataNotFoundException e) {
                        options = dhcpOptionSets.save(DhcpOptionSet.createDefault(vpcOwnerFullName,
                                Identifier.dopt.generate(), VmInstances.INSTANCE_SUBDOMAIN));
                    }
                    vpc = vpcs.save(Vpc.create(vpcOwnerFullName, Identifier.vpc.generate(), options, vpcCidr,
                            createDefault));
                    routeTable = routeTables.save(RouteTable.create(vpcOwnerFullName, vpc,
                            Identifier.rtb.generate(), vpc.getCidr(), true));
                    networkAcl = networkAcls
                            .save(NetworkAcl.create(vpcOwnerFullName, vpc, Identifier.acl.generate(), true));
                    final NetworkGroup group = NetworkGroup.create(vpcOwnerFullName, vpc,
                            ResourceIdentifiers.generateString(NetworkGroup.ID_PREFIX),
                            NetworkGroups.defaultNetworkName(), "default VPC security group");
                    final Collection<NetworkPeer> peers = Lists.newArrayList(NetworkPeer
                            .create(group.getOwnerAccountNumber(), group.getName(), group.getGroupId()));
                    group.addNetworkRules(Lists.newArrayList(
                            NetworkRule.create(null/*protocol name*/, -1, null/*low port*/, null/*high port*/,
                                    peers, null/*cidrs*/ ),
                            NetworkRule.createEgress(null/*protocol name*/, -1, null/*low port*/,
                                    null/*high port*/, null/*peers*/, Collections.singleton("0.0.0.0/0"))));
                    securityGroups.save(group);
                }
                if (createDefault && routeTable != null && networkAcl != null) {
                    // ensure there is an internet gateway for the vpc and a route in place
                    InternetGateway internetGateway;
                    try {
                        internetGateway = internetGateways.lookupByVpc(vpcAccountFullName, vpc.getDisplayName(),
                                Functions.<InternetGateway>identity());
                    } catch (final VpcMetadataNotFoundException e) {
                        internetGateway = internetGateways
                                .save(InternetGateway.create(vpcOwnerFullName, Identifier.igw.generate()));
                        internetGateway.setVpc(vpc);
                    }

                    final Optional<Route> defaultRoute = Iterables.tryFind(routeTable.getRoutes(),
                            CollectionUtils.propertyPredicate("0.0.0.0/0",
                                    RouteTables.RouteFilterStringFunctions.DESTINATION_CIDR));

                    if (!defaultRoute.isPresent()) {
                        routeTable.getRoutes().add(Route.create(routeTable, Route.RouteOrigin.CreateRouteTable,
                                "0.0.0.0/0", internetGateway));
                        routeTable.updateTimeStamps(); // ensure version of table increments also
                    }

                    // ensure there is a default subnet in each availability zone
                    final Set<String> cidrsInUse = Sets.newHashSet();
                    final Set<String> zonesWithoutSubnets = Sets.newTreeSet();
                    for (final String zone : Iterables.transform(Clusters.getInstance().listValues(),
                            CloudMetadatas.toDisplayName())) {
                        try {
                            cidrsInUse.add(subnets.lookupDefault(vpcAccountFullName, zone,
                                    Subnets.FilterStringFunctions.CIDR));
                        } catch (final VpcMetadataNotFoundException e) {
                            zonesWithoutSubnets.add(zone);
                        }
                    }
                    final List<String> subnetCidrs = Lists.newArrayList(
                            Iterables.transform(Cidr.parseUnsafe().apply(Vpcs.DEFAULT_VPC_CIDR).split(16),
                                    Functions.toStringFunction()));
                    subnetCidrs.removeAll(cidrsInUse);
                    for (final String zone : zonesWithoutSubnets) {
                        final Subnet subnet = subnets.save(Subnet.create(vpcOwnerFullName, vpc, networkAcl,
                                Identifier.subnet.generate(), subnetCidrs.remove(0), zone));
                        subnet.setDefaultForAz(true);
                        subnet.setMapPublicIpOnLaunch(true);
                    }
                }
                return vpc;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    };
    reply.setVpc(allocate(allocator, Vpc.class, VpcType.class));
    invalidate(reply.getVpc().getVpcId());
    return reply;
}