Example usage for com.google.common.collect Iterables toString

List of usage examples for com.google.common.collect Iterables toString

Introduction

In this page you can find the example usage for com.google.common.collect Iterables toString.

Prototype

public static String toString(Iterable<?> iterable) 

Source Link

Document

Returns a string representation of iterable , with the format [e1, e2, ..., en] (that is, identical to java.util.Arrays Arrays .toString(Iterables.toArray(iterable)) ).

Usage

From source file:com.google.devtools.build.lib.skyframe.packages.AbstractPackageLoader.java

private static NoSuchPackageException exceptionFromErrorInfo(ErrorInfo error, PackageIdentifier pkgId) {
    if (!Iterables.isEmpty(error.getCycleInfo())) {
        return new BuildFileContainsErrorsException(pkgId, "Cycle encountered while loading package " + pkgId);
    }/*from  ww  w  . j  ava 2 s .  c o m*/
    Throwable e = Preconditions.checkNotNull(error.getException());
    if (e instanceof NoSuchPackageException) {
        return (NoSuchPackageException) e;
    }
    throw new IllegalStateException("Unexpected Exception type from PackageValue for '" + pkgId
            + "'' with root causes: " + Iterables.toString(error.getRootCauses()), e);
}

From source file:com.android.idegen.Module.java

@Override
public String toString() {
    return Objects.toStringHelper(this).add("name", getName()).add("allDependencies", allDependencies)
            .add("iml files", allDependentImlFiles).add("imlFile", imlFile)
            .add("makeFileParser", makeFileParser)
            .add("explicitModuleNameDependencies", Iterables.toString(explicitModuleNameDependencies))
            .add("implicitModulePathDependencies", Iterables.toString(implicitModulePathDependencies))
            .toString();/*from   w w  w . j ava 2s  . c om*/
}

From source file:org.apache.brooklyn.location.jclouds.DefaultConnectivityResolver.java

/**
 * Returns the hosts and ports that should be considered when determining the address
 * to use when connecting to the location by assessing the following criteria:
 * <ol>//from  w  w w.j a  v  a  2s. com
 *     <li>Use the hostAndPortOverride set in options.</li>
 *     <li>If the machine is connectable, user credentials are given and the machine is provisioned
 *     in AWS then use {@link JcloudsLocation#getHostnameAws(NodeMetadata, Optional, Supplier, ConfigBag)}.</li>
 *     <li>If the machine is connectable and pollForFirstReachableAddress is set in options then use all
 *     {@link #getReachableAddresses reachable} addresses.</li>
 *     <li>Use the first address that is resolvable with {@link #isAddressResolvable}.</li>
 *     <li>Use the first address in the node's public then private addresses.</li>
 * </ol>
 */
protected Iterable<HostAndPort> getManagementCandidates(JcloudsLocation location, NodeMetadata node,
        ConfigBag config, ConnectivityResolverOptions options) {
    final Optional<HostAndPort> portForwardSshOverride = options.portForwardSshOverride();

    if (portForwardSshOverride.isPresent()) {
        // Don't try to resolve it; just use it
        int port = portForwardSshOverride.get().hasPort() ? portForwardSshOverride.get().getPort()
                : options.defaultLoginPort();
        final HostAndPort override = HostAndPort.fromParts(portForwardSshOverride.get().getHostText(), port);
        switch (getNetworkMode()) {
        case ONLY_PRIVATE:
            LOG.info(
                    "Ignoring mode {} in favour of port forwarding override for management candidates of {}: {}",
                    new Object[] { NetworkMode.ONLY_PRIVATE.name(), location, override });
            break;
        default:
            LOG.debug("Using host and port override for management candidates of {}: {}", location, override);
        }
        return ImmutableList.of(override);
    }

    if (options.pollForReachableAddresses() && options.reachableAddressPredicate() != null) {
        LOG.debug("Using reachable addresses for management candidates of {}", location);
        try {
            final Predicate<? super HostAndPort> predicate = options.reachableAddressPredicate();
            return getReachableAddresses(node, predicate, options.reachableAddressTimeout());
        } catch (RuntimeException e) {
            if (options.propagatePollForReachableFailure()) {
                throw Exceptions.propagate(e);
            } else {
                LOG.warn(
                        "No reachable address ({}/{}); falling back to any advertised address; may cause future failures",
                        location.getCreationString(config), node);
            }
        }
    } else if (options.pollForReachableAddresses()) {
        throw new IllegalStateException(this + " was configured to expect " + node + " to be reachable "
                + "and to poll for its reachable addresses but the predicate to determine reachability was null");
    }

    Iterable<String> addresses = getResolvableAddressesWithMode(node);
    LOG.debug("Using first resolvable address in {} for management candidates of {}",
            Iterables.toString(addresses), location);
    for (String address : addresses) {
        if (isAddressResolvable(address)) {
            return ImmutableList.of(HostAndPort.fromParts(address, options.defaultLoginPort()));
        } else {
            LOG.debug("Unresolvable address: " + address);
        }
    }

    LOG.warn("No resolvable address in {} ({}/{}); using first; may cause future failures",
            new Object[] { addresses, location.getCreationString(config), node });
    String host = Iterables.getFirst(addresses, null);
    if (host != null) {
        return ImmutableList.of(HostAndPort.fromParts(host, options.defaultLoginPort()));
    } else {
        return ImmutableList.of();
    }
}

From source file:brooklyn.entity.container.docker.DockerInfrastructureImpl.java

/**
 * De-register our {@link DockerLocation} and its children.
 *///from   w  ww . j av  a  2s.co  m
@Override
public void stop() {
    setAttribute(SERVICE_UP, Boolean.FALSE);
    Duration timeout = config().get(SHUTDOWN_TIMEOUT);

    // Find all applications and stop, blocking for up to five minutes until ended
    try {
        Iterable<Entity> entities = Iterables.filter(getManagementContext().getEntityManager().getEntities(),
                DockerUtils.sameInfrastructure(this));
        Set<Application> applications = ImmutableSet
                .copyOf(Iterables.transform(entities, new Function<Entity, Application>() {
                    @Override
                    public Application apply(Entity input) {
                        return input.getApplication();
                    }
                }));
        LOG.debug("Stopping applications: {}", Iterables.toString(applications));
        Entities.invokeEffectorList(this, applications, Startable.STOP).get(timeout);
    } catch (Exception e) {
        LOG.warn("Error stopping applications", e);
    }

    // Shutdown SDN if configured
    if (config().get(SDN_ENABLE)) {
        try {
            Entity sdn = getAttribute(SDN_PROVIDER);
            LOG.debug("Stopping SDN: {}", sdn);
            Entities.invokeEffector(this, sdn, Startable.STOP).get(timeout);
        } catch (Exception e) {
            LOG.warn("Error stopping SDN", e);
        }
    }

    // Stop all Docker hosts in parallel
    try {
        DynamicCluster hosts = getAttribute(DOCKER_HOST_CLUSTER);
        LOG.debug("Stopping hosts: {}", Iterables.toString(hosts.getMembers()));
        Entities.invokeEffectorList(this, hosts.getMembers(), Startable.STOP).get(timeout);
    } catch (Exception e) {
        LOG.warn("Error stopping hosts", e);
    }

    // Stop anything else left over
    super.stop();

    deleteLocation();
}

From source file:org.jclouds.vcloud.director.v1_5.domain.Checks.java

public static void checkNetworkConfiguration(NetworkConfiguration config) {
    // required//from  w w w  .ja v  a 2  s .c o m
    assertNotNull(config.getFenceMode(), String.format(OBJ_FIELD_REQ, "NetworkConfiguration", "fenceMode"));
    assertTrue(Network.FenceMode.ALL.contains(config.getFenceMode()),
            String.format(REQUIRED_VALUE_OBJECT_FMT, "fenceMode", "NetworkConfiguration", config.getFenceMode(),
                    Iterables.toString(Network.FenceMode.ALL)));

    // Check optional fields
    // NOTE retainNetInfoAcrossDeployments cannot be checked
    if (config.getIpScope() != null) {
        checkIpScope(config.getIpScope());
    }
    if (config.getParentNetwork() != null) {
        checkReferenceType(config.getParentNetwork());
    }
    if (config.getNetworkFeatures() != null) {
        checkNetworkFeatures(config.getNetworkFeatures());
    }
    if (config.getSyslogServerSettings() != null) {
        checkSyslogServerSettings(config.getSyslogServerSettings());
    }
    if (config.getRouterInfo() != null) {
        checkRouterInfo(config.getRouterInfo());
    }
}

From source file:clocker.docker.entity.DockerInfrastructureImpl.java

/**
 * De-register our {@link DockerLocation} and its children.
 *///from  www  .jav  a2 s.c om
@Override
public void stop() {
    sensors().set(SERVICE_UP, Boolean.FALSE);
    ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPING);
    Duration timeout = config().get(SHUTDOWN_TIMEOUT);

    deleteLocation();

    // Shutdown the Registry if configured
    if (config().get(DOCKER_SHOULD_START_REGISTRY)) {
        Entity registry = sensors().get(DOCKER_IMAGE_REGISTRY);
        DockerUtils.stop(this, registry, Duration.THIRTY_SECONDS);
    }

    // Find all applications and stop, blocking for up to five minutes until ended
    try {
        Iterable<Entity> entities = Iterables.filter(getManagementContext().getEntityManager().getEntities(),
                Predicates.and(DockerUtils.sameInfrastructure(this),
                        Predicates.not(EntityPredicates.applicationIdEqualTo(getApplicationId()))));
        Set<Application> applications = ImmutableSet
                .copyOf(Iterables.transform(entities, new Function<Entity, Application>() {
                    @Override
                    public Application apply(Entity input) {
                        return input.getApplication();
                    }
                }));
        LOG.debug("Stopping applications: {}", Iterables.toString(applications));
        Entities.invokeEffectorList(this, applications, Startable.STOP).get(timeout);
    } catch (Exception e) {
        LOG.warn("Error stopping applications", e);
    }

    // Stop all Docker hosts in parallel
    try {
        DynamicCluster hosts = getDockerHostCluster();
        LOG.debug("Stopping hosts: {}", Iterables.toString(hosts.getMembers()));
        Entities.invokeEffectorList(this, hosts.getMembers(), Startable.STOP).get(timeout);
    } catch (Exception e) {
        LOG.warn("Error stopping hosts", e);
    }

    ServiceStateLogic.setExpectedState(this, Lifecycle.STOPPED);
}

From source file:clocker.docker.entity.container.DockerContainerImpl.java

public void configurePortBindings(DockerHost host, Entity entity) {
    Collection<IpPermission> ipPermissions = getIpPermissions(entity);
    if (ipPermissions.size() > 0) {
        LOG.debug("Adding security group entries for forwarded ports on {}: {}", entity,
                Iterables.toString(ipPermissions));
        host.addIpPermissions(ipPermissions);
    }/*  ww w .  j  ava 2  s  .  co  m*/
}

From source file:org.apache.brooklyn.container.location.kubernetes.KubernetesLocation.java

protected boolean findResourceAddress(LocationSpec<? extends KubernetesMachineLocation> locationSpec,
        Entity entity, HasMetadata metadata, String resourceType, String resourceName, String namespace) {
    if (resourceType.equals(KubernetesResource.DEPLOYMENT)
            || resourceType.equals(KubernetesResource.REPLICATION_CONTROLLER)
            || resourceType.equals(KubernetesResource.POD)) {
        Map<String, String> labels = MutableMap.of();
        if (resourceType.equals(KubernetesResource.DEPLOYMENT)) {
            Deployment deployment = (Deployment) metadata;
            labels = deployment.getSpec().getTemplate().getMetadata().getLabels();
        } else if (resourceType.equals(KubernetesResource.REPLICATION_CONTROLLER)) {
            ReplicationController replicationController = (ReplicationController) metadata;
            labels = replicationController.getSpec().getTemplate().getMetadata().getLabels();
        }//from  w  w w  .  ja v a2 s. c o  m
        Pod pod = resourceType.equals(KubernetesResource.POD) ? getPod(namespace, resourceName)
                : getPod(namespace, labels);
        entity.sensors().set(KubernetesPod.KUBERNETES_POD, pod.getMetadata().getName());

        InetAddress node = Networking.getInetAddressWithFixedName(pod.getSpec().getNodeName());
        String podAddress = pod.getStatus().getPodIP();

        locationSpec.configure("address", node);
        locationSpec.configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableSet.of(podAddress));

        return true;
    } else if (resourceType.equals(KubernetesResource.SERVICE)) {
        getService(namespace, resourceName);
        Endpoints endpoints = client.endpoints().inNamespace(namespace).withName(resourceName).get();
        Set<String> privateIps = Sets.newLinkedHashSet();
        Set<String> podNames = Sets.newLinkedHashSet();
        for (EndpointSubset subset : endpoints.getSubsets()) {
            for (EndpointAddress address : subset.getAddresses()) {
                String podName = address.getTargetRef().getName();
                podNames.add(podName);
                String privateIp = address.getIp();
                privateIps.add(privateIp);
            }
        }
        locationSpec.configure(SshMachineLocation.PRIVATE_ADDRESSES, ImmutableSet.copyOf(privateIps));

        if (podNames.size() > 0) {
            // Use the first pod name from the list; warn when multiple pods are referenced
            String podName = Iterables.get(podNames, 0);
            if (podNames.size() > 1) {
                LOG.warn("Multiple pods referenced by service {} in namespace {}, using {}: {}",
                        new Object[] { resourceName, namespace, podName, Iterables.toString(podNames) });
            }
            try {
                Pod pod = getPod(namespace, podName);
                entity.sensors().set(KubernetesPod.KUBERNETES_POD, podName);

                InetAddress node = Networking.getInetAddressWithFixedName(pod.getSpec().getNodeName());
                locationSpec.configure("address", node);
            } catch (KubernetesClientException kce) {
                LOG.warn("Cannot find pod {} in namespace {} for service {}",
                        new Object[] { podName, namespace, resourceName });
            }
        }

        return true;
    } else {
        return false;
    }
}

From source file:org.apache.brooklyn.entity.group.DynamicClusterImpl.java

protected List<Location> findSubLocations(Location loc) {
    if (!loc.hasExtension(AvailabilityZoneExtension.class)) {
        throw new IllegalStateException("Availability zone extension not supported for location " + loc);
    }/*from   w  w w  .ja v  a 2 s .c om*/

    AvailabilityZoneExtension zoneExtension = loc.getExtension(AvailabilityZoneExtension.class);

    Collection<String> zoneNames = getConfig(AVAILABILITY_ZONE_NAMES);
    Integer numZones = getConfig(NUM_AVAILABILITY_ZONES);

    List<Location> subLocations;
    if (zoneNames == null || zoneNames.isEmpty()) {
        if (numZones != null) {
            subLocations = zoneExtension.getSubLocations(numZones);

            checkArgument(numZones > 0, "numZones must be greater than zero: %s", numZones);
            if (numZones > subLocations.size()) {
                throw new IllegalStateException("Number of required zones (" + numZones + ") not satisfied in "
                        + loc + "; only " + subLocations.size() + " available: " + subLocations);
            }
        } else {
            subLocations = zoneExtension.getAllSubLocations();
        }
    } else {
        // TODO check that these are valid region / availabilityZones?
        subLocations = zoneExtension.getSubLocationsByName(StringPredicates.equalToAny(zoneNames),
                zoneNames.size());

        if (zoneNames.size() > subLocations.size()) {
            throw new IllegalStateException(
                    "Number of required zones (" + zoneNames.size() + " - " + zoneNames + ") not satisfied in "
                            + loc + "; only " + subLocations.size() + " available: " + subLocations);
        }
    }

    LOG.info("Returning {} sub-locations: {}", subLocations.size(), Iterables.toString(subLocations));
    return subLocations;
}

From source file:clocker.docker.entity.container.DockerContainerImpl.java

public void removePortBindings(DockerHost host, Entity entity) {
    Collection<IpPermission> ipPermissions = getIpPermissions(entity);
    if (ipPermissions.size() > 0) {
        LOG.debug("Removing security group entries for forwarded ports on {}: {}", entity,
                Iterables.toString(ipPermissions));
        host.removeIpPermissions(ipPermissions);
    }//w  ww  .j  a  v a  2s.com
}