@Test(dependsOnMethods = "testCreateLoadBalancer")
  public void testCreateAndGetSessionPersistence() throws Exception {
    api.getSessionPersistenceApi(region, lb.getId()).create(SessionPersistence.HTTP_COOKIE);
    assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));

    SessionPersistence sessionPersistence = api.getSessionPersistenceApi(region, lb.getId()).get();

    assertEquals(sessionPersistence, SessionPersistence.HTTP_COOKIE);
  }
  @Test(dependsOnMethods = "testCreateAndGetSessionPersistence")
  public void testRemoveAndGetSessionPersistence() throws Exception {
    api.getSessionPersistenceApi(region, lb.getId()).delete();
    assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));

    SessionPersistence sessionPersistence = api.getSessionPersistenceApi(region, lb.getId()).get();

    assertNull(sessionPersistence);
  }
  private LoadBalancer getLoadBalancer() {
    for (LoadBalancer loadBalancer : lbApi.list().concat()) {
      if (loadBalancer.getName().startsWith(Constants.NAME)) {
        return loadBalancer;
      }
    }

    throw new RuntimeException(
        Constants.NAME + " not found. Run a CreateLoadBalancer* example first.");
  }
 @Override
 @AfterGroups(groups = "live")
 protected void tearDown() {
   assertTrue(awaitAvailable(api.getLoadBalancerApi(region)).apply(lb));
   api.getLoadBalancerApi(region).delete(lb.getId());
   assertTrue(awaitDeleted(api.getLoadBalancerApi(region)).apply(lb));
   super.tearDown();
 }
  private Set<Node> getNodes(LoadBalancer loadBalancer) {
    NodeApi nodeApi = clb.getNodeApiForZoneAndLoadBalancer(Constants.ZONE, loadBalancer.getId());
    Set<Node> nodes = Sets.newHashSet();

    for (Node node : nodeApi.list().concat()) {
      if (node.getAddress().startsWith("10.180.1")) {
        nodes.add(node);
      }
    }

    return nodes;
  }
  private void removeNodesFromLoadBalancer(Set<Node> nodes, LoadBalancer loadBalancer)
      throws TimeoutException {
    System.out.println("Remove Nodes");

    NodeApi nodeApi = clb.getNodeApiForZoneAndLoadBalancer(Constants.ZONE, loadBalancer.getId());
    Iterable<Integer> nodeIds = Iterables.transform(nodes, new NodeToInteger());

    nodeApi.remove(nodeIds);

    // Wait for the Load Balancer to become Active before moving on
    // If you want to know what's happening during the polling, enable logging. See
    // /jclouds-example/rackspace/src/main/java/org/jclouds/examples/rackspace/Logging.java
    if (!LoadBalancerPredicates.awaitAvailable(lbApi).apply(loadBalancer)) {
      throw new TimeoutException("Timeout on loadBalancer: " + loadBalancer);
    }

    System.out.println("  " + nodeIds);
  }
  @Override
  public LoadBalancer apply(LB lb) {
    try {
      Builder builder =
          LoadBalancer.builder()
              .id(lb.id)
              .region(region)
              .status(lb.status)
              .name(lb.getName())
              .protocol(lb.getProtocol())
              .port(lb.getPort())
              .nodeCount(lb.nodeCount)
              .nodes(lb.getNodes())
              .timeout(lb.getTimeout())
              .algorithm(lb.getAlgorithm())
              .halfClosed(lb.isHalfClosed())
              .sessionPersistenceType(lb.getSessionPersistenceType())
              .connectionLogging(lb.isConnectionLogging())
              .connectionThrottle(lb.getConnectionThrottle())
              .healthMonitor(lb.getHealthMonitor());

      if (lb.cluster.size() == 1) builder.clusterName(Iterables.get(lb.cluster.values(), 0));
      if (lb.created.size() == 1) builder.created(Iterables.get(lb.created.values(), 0));
      if (lb.updated.size() == 1) builder.updated(Iterables.get(lb.updated.values(), 0));
      if (lb.contentCaching.size() == 1)
        builder.contentCaching(Iterables.get(lb.contentCaching.values(), 0));
      if (lb.sslTermination != null) builder.sslTermination(lb.sslTermination);
      if (lb.sourceAddresses != null) builder.sourceAddresses(lb.sourceAddresses);
      if (lb.accessList == null) builder.accessRules(ImmutableSet.<AccessRuleWithId>of());
      else builder.accessRules(lb.accessList);
      if (lb.virtualIps == null) builder.virtualIPs(ImmutableSet.<VirtualIPWithId>of());
      else builder.virtualIPs(lb.virtualIps);
      if (lb.metadata == null) builder.metadata(new Metadata());
      else builder.metadata(ParseMetadata.transformCLBMetadataToMetadata(lb.metadata));

      return builder.build();
    } catch (NullPointerException e) {
      logger.warn(e, "nullpointer found parsing %s", lb);
      throw e;
    }
  }
  private void updateLoadBalancer(LoadBalancer loadBalancer) throws TimeoutException {
    System.out.println("Update Load Balancer");

    UpdateLoadBalancer updateLB =
        UpdateLoadBalancer.builder()
            .name(Constants.NAME + "-update")
            .protocol("HTTPS")
            .port(443)
            .algorithm(LoadBalancer.Algorithm.RANDOM)
            .build();

    lbApi.update(loadBalancer.getId(), updateLB);

    // Wait for the Load Balancer to become Active before moving on
    // If you want to know what's happening during the polling, enable logging. See
    // /jclouds-example/rackspace/src/main/java/org/jclouds/examples/rackspace/Logging.java
    if (!LoadBalancerPredicates.awaitAvailable(lbApi).apply(loadBalancer)) {
      throw new TimeoutException("Timeout on loadBalancer: " + loadBalancer);
    }

    System.out.println("  " + true);
  }
  @Override
  public LoadBalancer expected() {
    Metadata metadata = new Metadata();
    metadata.put("color", "red");
    metadata.putId("color", 1);
    metadata.put("label", "web-load-balancer");
    metadata.putId("label", 2);

    return LoadBalancer.builder()
        .region("DFW")
        .id(2000)
        .name("sample-loadbalancer")
        .protocol("HTTP")
        .port(80)
        .algorithm(Algorithm.RANDOM)
        .status(Status.ACTIVE)
        .connectionLogging(true)
        .contentCaching(true)
        .nodeCount(2)
        .halfClosed(false)
        .healthMonitor(
            HealthMonitor.builder()
                .type(Type.CONNECT)
                .delay(10)
                .timeout(5)
                .attemptsBeforeDeactivation(2)
                .build())
        .sslTermination(
            SSLTermination.builder().enabled(true).secureTrafficOnly(false).securePort(443).build())
        .sourceAddresses(
            SourceAddresses.builder()
                .ipv6Public("2001:4800:7901::5/64")
                .ipv4Public("174.143.139.137")
                .ipv4Servicenet("10.183.250.137")
                .build())
        .connectionThrottle(
            ConnectionThrottle.builder()
                .maxConnections(100)
                .minConnections(10)
                .maxConnectionRate(50)
                .rateInterval(60)
                .build())
        .accessRules(
            ImmutableSet.of(
                new AccessRuleWithId(22215, "1.2.3.4/32", AccessRule.Type.DENY),
                new AccessRuleWithId(22217, "12.0.0.0/8", AccessRule.Type.ALLOW)))
        .virtualIPs(
            ImmutableSet.of(
                new VirtualIPWithId(
                    VirtualIP.Type.PUBLIC, VirtualIP.IPVersion.IPV4, 1000, "206.10.10.210"),
                new VirtualIPWithId(
                    VirtualIP.Type.PUBLIC,
                    VirtualIP.IPVersion.IPV6,
                    1001,
                    "2001:4800:7901:0000:9a32:3c2a:0000:0001")))
        .nodes(
            ImmutableSet.of(
                Node.builder()
                    .id(1041)
                    .address("10.1.1.1")
                    .port(80)
                    .condition(Node.Condition.ENABLED)
                    .status(Node.Status.ONLINE)
                    .build(),
                Node.builder()
                    .id(1411)
                    .address("10.1.1.2")
                    .port(80)
                    .condition(Node.Condition.ENABLED)
                    .status(Node.Status.ONLINE)
                    .build()))
        .sessionPersistenceType(SessionPersistence.HTTP_COOKIE)
        .clusterName("c1.dfw1")
        .created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2010-11-30T03:23:42Z"))
        .updated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2010-11-30T03:23:44Z"))
        .metadata(metadata)
        .uri(
            URI.create(
                "https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/123123/loadbalancers/2000"))
        .build();
  }