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

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

Introduction

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

Prototype

public static <T> T get(Iterable<T> iterable, int position) 

Source Link

Document

Returns the element at the specified position in an iterable.

Usage

From source file:com.eucalyptus.auth.euare.EuareRemoteRegionService.java

private <R extends IdentityMessage> R send( //TODO:STEVE: move send to a helper (also RemoteIdentityProvider#send)
        final Optional<RegionInfo> region, final IdentityMessage request) throws Exception {
    final Optional<Set<String>> endpoints = region.transform(RegionInfo.serviceEndpoints("identity"));
    final ServiceConfiguration config = new EphemeralConfiguration(ComponentIds.lookup(Identity.class),
            "identity", "identity", URI.create(Iterables.get(endpoints.get(), 0))); //TODO:STEVE: endpoint handling
    return AsyncRequests.sendSync(config, request);
}

From source file:org.apache.whirr.service.hadoop.HadoopService.java

private Set<Instance> getInstances(final Set<String> roles, Set<? extends NodeMetadata> nodes) {
    return Sets/*w  ww. ja v  a  2  s.  com*/
            .newHashSet(Collections2.transform(Sets.newHashSet(nodes), new Function<NodeMetadata, Instance>() {
                @Override
                public Instance apply(NodeMetadata node) {
                    return new Instance(roles, Iterables.get(node.getPublicAddresses(), 0),
                            Iterables.get(node.getPrivateAddresses(), 0));
                }
            }));
}

From source file:com.github.benmanes.caffeine.cache.NodeGenerator.java

private void addValue() {
    if (!isBaseClass()) {
        return;/*from  w  w  w  . ja  v a2 s  . c o m*/
    }
    Strength valueStrength = strengthOf(Iterables.get(generateFeatures, 1));
    nodeSubtype.addField(newFieldOffset(className, "value")).addField(newValueField())
            .addMethod(newGetter(valueStrength, vTypeVar, "value", Visibility.LAZY)).addMethod(makeSetValue())
            .addMethod(makeContainsValue());
    addValueConstructorAssignment(constructorByKey);
    addValueConstructorAssignment(constructorByKeyRef);
}

From source file:brooklyn.util.internal.ssh.SshAbstractTool.java

protected SshAbstractTool(AbstractSshToolBuilder<?, ?> builder) {
    super(builder.localTempDir);

    host = checkNotNull(builder.host, "host");
    port = builder.port;// w  ww  . j  a v a 2  s.  co  m
    user = builder.user;
    password = builder.password;
    strictHostKeyChecking = builder.strictHostKeyChecking;
    allocatePTY = builder.allocatePTY;
    privateKeyPassphrase = builder.privateKeyPassphrase;
    privateKeyData = builder.privateKeyData;

    if (builder.privateKeyFiles.size() > 1) {
        throw new IllegalArgumentException("sshj supports only a single private key-file; "
                + "for defaults of ~/.ssh/id_rsa and ~/.ssh/id_dsa leave blank");
    } else if (builder.privateKeyFiles.size() == 1) {
        String privateKeyFileStr = Iterables.get(builder.privateKeyFiles, 0);
        String amendedKeyFile = privateKeyFileStr.startsWith("~")
                ? (System.getProperty("user.home") + privateKeyFileStr.substring(1))
                : privateKeyFileStr;
        privateKeyFile = new File(amendedKeyFile);
    } else {
        privateKeyFile = null;
    }

    checkArgument(host.length() > 0, "host value must not be an empty string");
    checkPortValid(port, "ssh port");

    toString = String.format("%s@%s:%d", user, host, port);
}

From source file:com.google.api.server.spi.config.jsonwriter.JsonConfigWriter.java

private String generateForApi(Iterable<? extends ApiConfig> apiConfigs) throws ApiConfigException {
    ObjectNode root = objectMapper.createObjectNode();
    // First, generate api-wide configuration options, given any ApiConfig.
    ApiConfig apiConfig = Iterables.get(apiConfigs, 0);
    convertApi(root, apiConfig);//from ww  w . j a v  a2  s. c om
    convertApiAuth(root, apiConfig.getAuthConfig());
    convertApiFrontendLimits(root, apiConfig.getFrontendLimitsConfig());
    convertApiCacheControl(root, apiConfig.getCacheControlConfig());
    convertApiNamespace(root, apiConfig.getNamespaceConfig());
    // Next, generate config-specific configuration options,
    convertApiMethods(apiConfigs, root);
    return toString(root);
}

From source file:com.cinchapi.common.collect.Association.java

/**
 * Return a possibly nested value from within the {@link Association}.
 * /*from  w  ww . jav a  2  s .  c  om*/
 * @param path a navigable path key (e.g. foo.bar.1.baz)
 * @return the value
 */
@SuppressWarnings("unchecked")
@Nullable
public <T> T fetch(String path) {
    T value = (T) exploded.get(path); // first, check to see if the path has
                                      // been directly added to the map
    if (value == null) {
        String[] components = path.split("\\.");
        Verify.thatArgument(components.length > 0, "Invalid path " + path);
        Object source = exploded;
        for (String component : components) {
            Integer index;
            if (source == null) {
                break;
            } else if ((index = Ints.tryParse(component)) != null) {
                if (source instanceof Collection && ((Collection<T>) source).size() > index) {
                    source = Iterables.get((Collection<T>) source, index);
                } else {
                    source = null;
                }
            } else {
                source = source instanceof Map ? ((Map<String, Object>) source).get(component) : null;
            }
        }
        return source != null ? (T) source : null;
    } else {
        return value;
    }
}

From source file:com.google.devtools.build.lib.util.ResourceUsage.java

/**
 * Returns the current total idle time of the processors since system boot.
 * Reads /proc/stat to obtain this information.
 *//*from   ww  w .  j  av a  2s. c o  m*/
private static long getCurrentTotalIdleTimeInJiffies() {
    try {
        File file = new File("/proc/stat");
        String content = Files.toString(file, US_ASCII);
        String value = Iterables.get(WHITESPACE_SPLITTER.split(content), 5);
        return Long.parseLong(value);
    } catch (NumberFormatException | IOException e) {
        return 0L;
    }
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

/**
 * Tests server start, reboot and deletion. Also verifies IP services and job services.
 *///from   w w  w  .j  a va2 s.  c o  m
@Test(enabled = true)
public void testServerLifecycle() {
    int serverCountBeforeTest = api.getServerServices().getServerList().size();

    final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
    serversToDeleteAfterTheTests.add(nameOfServer);

    Set<Ip> availableIps = api.getIpServices().getUnassignedPublicIpList();
    Ip availableIp = Iterables.getLast(availableIps);

    String ram = Iterables.get(api.getServerServices().getRamSizes(), 0).getName();

    Server createdServer = api.getServerServices().addServer(nameOfServer,
            "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, availableIp.getIp());
    assertNotNull(createdServer);
    assert serverLatestJobCompleted.apply(createdServer);

    // get server by name
    Set<Server> response = api.getServerServices().getServersByName(nameOfServer);
    assert (response.size() == 1);

    // restart the server
    api.getServerServices().power(nameOfServer, PowerCommand.RESTART);

    Set<Job> jobs = api.getJobServices().getJobsForObjectName(nameOfServer);
    assert ("RestartVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName()));

    assert serverLatestJobCompleted.apply(createdServer);

    int serverCountAfterAddingOneServer = api.getServerServices().getServerList().size();
    assert serverCountAfterAddingOneServer == serverCountBeforeTest
            + 1 : "There should be +1 increase in the number of servers since the test started";

    // delete the server
    api.getServerServices().deleteByName(nameOfServer);

    jobs = api.getJobServices().getJobsForObjectName(nameOfServer);
    assert ("DeleteVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName()));

    assert serverLatestJobCompleted.apply(createdServer);

    int serverCountAfterDeletingTheServer = api.getServerServices().getServerList().size();
    assert serverCountAfterDeletingTheServer == serverCountBeforeTest : "There should be the same # of servers as since the test started";

    // make sure that IP is put back to "unassigned"
    assert api.getIpServices().getUnassignedIpList().contains(availableIp);
}

From source file:cd.go.contrib.elasticagents.marathon.MarathonInstance.java

public static MarathonInstance instanceFromApp(App app, PluginSettings settings) {
    Map<String, String> autoRegisterProperties = new HashMap<>();
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_KEY", app.getEnv().get("GO_EA_AUTO_REGISTER_KEY"));
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_ENVIRONMENT",
            app.getEnv().get("GO_EA_AUTO_REGISTER_ENVIRONMENT"));
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_ELASTIC_AGENT_ID",
            app.getEnv().get("GO_EA_AUTO_REGISTER_ELASTIC_AGENT_ID"));
    autoRegisterProperties.put("GO_EA_AUTO_REGISTER_ELASTIC_PLUGIN_ID",
            app.getEnv().get("GO_EA_AUTO_REGISTER_ELASTIC_PLUGIN_ID"));

    DateTime createdTime = new DateTime();

    if (app.getTasks() != null) {
        if (app.getTasks().size() > 0) {
            createdTime = new DateTime(Iterables.get(app.getTasks(), 0).getStagedAt());
        }/*from   w ww  .  j a v  a2s.c om*/
    }

    Gson gson = new Gson();
    List<String> constraintList = new ArrayList<>();

    for (List<String> constraint : app.getConstraints()) {
        constraintList.add(gson.toJson(constraint));
    }
    String constraints = String.join("\n", constraintList);

    String uris = app.getUris() == null ? "" : String.join("\n", app.getUris());

    List<String> volumes = new ArrayList<>();
    if (app.getContainer().getVolumes() != null) {
        for (Volume volume : app.getContainer().getVolumes()) {
            volumes.add(volume.getContainerPath() + ":" + volume.getHostPath() + ":" + volume.getMode());
        }
    }
    String vols = String.join("\n", volumes);

    return new MarathonInstance(app.getId().substring(settings.getMarathonPrefix().length()), createdTime,
            app.getEnv().get("GO_EA_AUTO_REGISTER_ENVIRONMENT"), settings.getGoServerUrl(),
            settings.getMarathonPrefix(), app.getContainer().getDocker().getImage(), app.getMem(),
            app.getCpus(), app.getCmd(), app.getEnv().get("GO_EA_USER"), constraints, uris, vols,
            autoRegisterProperties);
}

From source file:net.lldp.checksims.algorithm.smithwaterman.SmithWatermanAlgorithm.java

/**
 * Compute a Smith-Waterman alignment through exhaustive (but more reliable) process.
 *
 * TODO tests for this (already tested through SmithWaterman)
 *
 * @return Pair of TokenList representing optimal alignments
 * @throws InternalAlgorithmError Thrown if internal error causes violation of preconditions
 *//*  w ww  . ja v  a  2s  .  c  o m*/
public Pair<TokenList, TokenList> computeSmithWatermanAlignmentExhaustive() throws InternalAlgorithmError {
    Map<Integer, Set<Coordinate>> localCandidates;

    // Keep computing while we have results over threshold
    do {
        // Recompute whole array
        localCandidates = computeArraySubset(wholeArray);

        if (localCandidates.isEmpty()) {
            break;
        }

        // Get the largest key
        int largestKey = Ordering.natural().max(localCandidates.keySet());

        // Get matching coordinates
        Set<Coordinate> largestCoords = localCandidates.get(largestKey);

        if (largestCoords == null || largestCoords.isEmpty()) {
            throw new InternalAlgorithmError(
                    "Error: largest key " + largestKey + " maps to null or empty candidate set!");
        }

        // Arbitrarily break ties
        Coordinate chosenCoord = Iterables.get(largestCoords, 0);

        // Get match coordinates
        Set<Coordinate> matchCoords = getMatchCoordinates(chosenCoord);

        // Set match invalid
        setMatchesInvalid(matchCoords);
    } while (!localCandidates.isEmpty());

    // IntelliJ has an aversion to passing anything with a 'y' in it as the right side of a pair
    // This alleviates the warning
    //noinspection SuspiciousNameCombination
    return Pair.of(xList, yList);
}