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

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

Introduction

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

Prototype

public static <T> T getOnlyElement(Iterable<T> iterable) 

Source Link

Document

Returns the single element contained in iterable .

Usage

From source file:org.jclouds.examples.ec2.spot.MainApp.java

public static void main(String[] args) {

    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    // Args/*ww w  .j av a  2 s.c  o m*/
    String accesskeyid = args[0];
    String secretkey = args[1];
    String group = args[2];
    String command = args[3];

    // Init
    ComputeService compute = new ComputeServiceContextFactory().createContext("aws-ec2", accesskeyid, secretkey)
            .getComputeService();

    // wait up to 60 seconds for ssh to be accessible
    RetryablePredicate<IPSocket> socketTester = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(),
            60, 1, 1, TimeUnit.SECONDS);
    try {
        if (command.equals("create")) {

            Template template = compute.templateBuilder().build();

            template.getOptions().as(AWSEC2TemplateOptions.class)
                    // set the price as 3 cents/hr
                    .spotPrice(0.03f)
                    // authorize my ssh key
                    .authorizePublicKey(Files.toString(
                            new File(System.getProperty("user.home") + "/.ssh/id_rsa.pub"), Charsets.UTF_8));

            System.out.printf(">> running one spot node type(%s) with ami(%s) in group(%s)%n",
                    template.getHardware().getProviderId(), template.getImage().getId(), group);
            // run only a single node
            NodeMetadata node = Iterables.getOnlyElement(compute.createNodesInGroup(group, 1, template));

            System.out.printf("<< running node(%s)%n", node.getId());
            IPSocket socket = new IPSocket(Iterables.get(node.getPublicAddresses(), 0), node.getLoginPort());
            if (socketTester.apply(socket)) {
                System.out.printf("<< socket ready [%s] node(%s)%n", socket, node.getId());
                System.out.printf("ssh to node with the following command:%n ssh %s@%s%n",
                        node.getCredentials().identity, socket.getAddress());
                System.exit(0);
            } else {
                System.out.printf("<< socket not ready [%s] node(%s)%n", socket, node.getId());
            }
        } else if (command.equals("destroy")) {
            System.out.printf(">> destroying nodes in group(%s)%n", group);
            Set<? extends NodeMetadata> destroyed = compute.destroyNodesMatching(NodePredicates.inGroup(group));
            System.out.printf("<< destroyed(%d)%n", destroyed.size());
            System.exit(0);
        } else {
            System.err.println(INVALID_SYNTAX);
            System.exit(1);
        }
    } catch (RunNodesException e) {
        System.err.println(e.getMessage());
        for (NodeMetadata node : e.getNodeErrors().keySet())
            compute.destroyNode(node.getId());
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } finally {
        compute.getContext().close();
    }

}

From source file:accumulo.AccumuloStuff.java

public static void main(String[] args) throws Exception {
    File tmp = new File(System.getProperty("user.dir") + "/target/mac-test");
    if (tmp.exists()) {
        FileUtils.deleteDirectory(tmp);//w  ww.j  a va 2  s .c o  m
    }
    tmp.mkdirs();
    String passwd = "password";

    MiniAccumuloConfigImpl cfg = new MiniAccumuloConfigImpl(tmp, passwd);
    cfg.setNumTservers(1);
    //    cfg.useMiniDFS(true);

    final MiniAccumuloClusterImpl cluster = cfg.build();
    setCoreSite(cluster);
    cluster.start();

    ExecutorService svc = Executors.newFixedThreadPool(2);

    try {
        Connector conn = cluster.getConnector("root", passwd);
        String table = "table";
        conn.tableOperations().create(table);

        final BatchWriter bw = conn.createBatchWriter(table, new BatchWriterConfig());
        final AtomicBoolean flushed = new AtomicBoolean(false);

        Runnable writer = new Runnable() {
            @Override
            public void run() {
                try {
                    Mutation m = new Mutation("row");
                    m.put("colf", "colq", "value");
                    bw.addMutation(m);
                    bw.flush();
                    flushed.set(true);
                } catch (Exception e) {
                    log.error("Got exception trying to flush mutation", e);
                }

                log.info("Exiting batchwriter thread");
            }
        };

        Runnable restarter = new Runnable() {
            @Override
            public void run() {
                try {
                    for (ProcessReference proc : cluster.getProcesses().get(ServerType.TABLET_SERVER)) {
                        cluster.killProcess(ServerType.TABLET_SERVER, proc);
                    }
                    cluster.exec(TabletServer.class);
                } catch (Exception e) {
                    log.error("Caught exception restarting tabletserver", e);
                }
                log.info("Exiting restart thread");
            }
        };

        svc.execute(writer);
        svc.execute(restarter);

        log.info("Waiting for shutdown");
        svc.shutdown();
        if (!svc.awaitTermination(120, TimeUnit.SECONDS)) {
            log.info("Timeout on shutdown exceeded");
            svc.shutdownNow();
        } else {
            log.info("Cleanly shutdown");
            log.info("Threadpool is terminated? " + svc.isTerminated());
        }

        if (flushed.get()) {
            log.info("****** BatchWriter was flushed *********");
        } else {
            log.info("****** BatchWriter was NOT flushed *********");
        }

        bw.close();

        log.info("Got record {}", Iterables.getOnlyElement(conn.createScanner(table, Authorizations.EMPTY)));
    } finally {
        cluster.stop();
    }
}

From source file:com.opengamma.financial.analytics.model.bondfutureoption.BondFutureOptionUtils.java

public static ExternalId getBloombergTicker(final BondFutureOptionSecurity security) {
    final ExternalIdBundle bundle = security.getExternalIdBundle();
    return Iterables.getOnlyElement(bundle.getExternalIds(ExternalSchemes.BLOOMBERG_TICKER));
}

From source file:com.google.devtools.build.skyframe.WalkableGraphUtils.java

public static Iterable<SkyKey> getDirectDeps(WalkableGraph graph, SkyKey key) throws InterruptedException {
    return Iterables.getOnlyElement(graph.getDirectDeps(ImmutableList.of(key)).values());
}

From source file:com.xebialabs.overcast.support.virtualbox.VirtualboxState.java

public static VirtualboxState fromStatusString(String s) {

    String stateString = Iterables.getOnlyElement(filter(Arrays.asList(s.split("\n")), new Predicate<String>() {
        @Override//  ww  w.  j av  a2  s  .  co  m
        public boolean apply(final String input) {
            return input.startsWith("State:");
        }
    }));

    if (stateString.contains("powered off")) {
        return POWEROFF;
    }

    if (stateString.contains("saved")) {
        return POWEROFF;
    }

    if (stateString.contains("aborted")) {
        return ABORTED;
    }

    if (stateString.contains("running")) {
        return RUNNING;
    }

    throw new IllegalStateException("Can not detect state for state string: " + stateString);
}

From source file:com.google.devtools.build.skyframe.WalkableGraphUtils.java

public static Iterable<SkyKey> getReverseDeps(WalkableGraph graph, SkyKey key) throws InterruptedException {
    return Iterables.getOnlyElement(graph.getReverseDeps(ImmutableList.of(key)).values());
}

From source file:org.apache.beam.sdk.extensions.euphoria.core.client.util.PCollectionLists.java

public static <T> PCollection<T> getOnlyElement(PCollectionList<T> inputs) {
    return Iterables.getOnlyElement(inputs.getAll());
}

From source file:com.dasasian.chok.util.ZkChokUtil.java

public static ZkServer startZkServer(ZkConfiguration conf) {
    String server = Iterables.getOnlyElement(COMMA_SPLITTER.split(conf.getServers()));
    HostAndPort hostAndPort = HostAndPort.fromString(server);
    if (!hostAndPort.hasPort()) {
        throw new IllegalArgumentException("No Port Specified for ZkServer");
    } else {/*w ww. j a va  2s.  c  o  m*/
        String host = hostAndPort.getHostText();
        //            if (!host.equals("127.0.0.1") && !host.equals("localhost")) {
        //                throw new IllegalArgumentException("Attempting to start ZkServer remotely on " + host + " valid values are 127.0.0.1 or localhost");
        //            }
    }
    ZkServer zkServer = new ZkServer(conf.getDataDir(), conf.getLogDataDir(), new DefaultNameSpaceImpl(conf),
            hostAndPort.getPort(), conf.getTickTime());
    zkServer.start();
    return zkServer;
}

From source file:org.apache.beam.fn.harness.data.MultiplexingFnDataReceiver.java

public static <T> FnDataReceiver<T> forConsumers(Collection<FnDataReceiver<T>> consumers) {
    if (consumers.size() == 1) {
        return Iterables.getOnlyElement(consumers);
    }/* w w w.j  ava  2s  .  com*/
    return new MultiplexingFnDataReceiver<>(consumers);
}

From source file:com.nesscomputing.testing.NessHttpserverHelper.java

static URI getServiceUri(Injector injector) {
    HttpServer server = injector.getInstance(HttpServer.class);
    HttpConnector connector = Iterables.getOnlyElement(server.getConnectors().values());
    try {/*from   w  w w .  j  a  v a  2  s . c  o m*/
        return new URI(connector.getScheme(), null, connector.getAddress(), connector.getPort(), null, null,
                null);
    } catch (URISyntaxException e) {
        throw new IllegalStateException(e);
    }
}