Example usage for com.google.common.io Files toString

List of usage examples for com.google.common.io Files toString

Introduction

In this page you can find the example usage for com.google.common.io Files toString.

Prototype

public static String toString(File file, Charset charset) throws IOException 

Source Link

Usage

From source file:net.sf.qualitycheck.immutableobject.Main.java

public static void main(final String[] args) throws IOException {
    Check.notNull(args, "args");
    LOG.info("This tool generates an immutable class from an interface.");
    LOG.info("--");
    LOG.info("--");
    if (args.length == 0) {
        LOG.info("Input a path to an interface, please.");
    }/*from   ww  w. j  ava  2s . c om*/
    LOG.info("--");
    for (final String path : args) {
        final File file = new File(path);
        final String code = Files.toString(file, Charsets.UTF_8);
        final String generated = ImmutableObjectGenerator.generate(code, defaultSettings()).getImplCode();
        LOG.info("\n" + generated);
    }
    LOG.info("--");
    LOG.info("We hope that you saved some time.");
    LOG.info("Your participation in this project is much appreciated!");
}

From source file:tv.icntv.test.Create.java

public static void main(String[] args) throws IOException {
    String json = Files.toString(new File("d:\\db.txt"), Charsets.UTF_8);
    ProgramSeries programSeries = JSON.parseObject(json, ProgramSeries.class);

    //        System.out.println(JSON.toJSONString(programSeries,true));
    //        System.out.println(ESJsonUtils.getIndexJson(programSeries).string());
    //        ProgramSeries p = new ProgramSeries();
    //        p.setBigPosterAddr("abc");
    //        p.setCopyRightZone(new String[]{"a", "b"});
    //        p.setCustomer(1);
    //        p.setGrade(9.8f);
    //        p.setId(3);
    //        p.setIs3d(0);
    //        p.setPlatformName(new String[]{"sanxing", "android"});
    //        p.setPosterAddr("http://baidu.com");
    //        p.setProgramHeader("xplg");
    //        p.setProgramLength(23);
    //        p.setProgramSeriesName("??");
    //        p.setProgramPinyin("xiaopingguo");
    //        p.setProgramSeriesEnName("abcdefg");
    //        p.setProgramTotalCount(4);
    //        TagSource tagSource = new TagSource();
    ////        tagSource.setId(2);
    ////        tagSource.setTagLevel(1);
    //        tagSource.setTagName("");
    //        TagSource child1 = new TagSource();
    ////        child1.setId(2);
    ////        child1.setTagLevel(2);
    //        child1.setTagName("");
    //        TagSource child2 = new TagSource();
    ////        child2.setId(3);
    ////        child2.setTagLevel(2);
    //        child2.setTagName("");
    //        tagSource.setChildTagSource(new TagSource[]{child1,child2});
    //        p.setTags(new TagSource[]{tagSource});
    //        System.out.println(JSON.toJSONString(p,true));
    //        System.out.println(ESJsonUtils.getIndexJson(p).string());
    Search search = Search.getInstance();
    //        Index index = new Index();
    //        index.createIndex(programSeries);
    TransportClient client = search.getESClient();
    //        client.admin().indices().delete(Requests.deleteIndexRequest("cms_v1")).actionGet();
    ////        client.prepareDelete().(Requests.deleteRequest("cms_v1")).actionGet();
    ////        Requests.indexRequest("abc").type("d").source(Create.getCreateMapping());
    //        client.admin().indices().prepareCreate(search.getIndex()).execute().actionGet();
    ////        System.out.println(ESJsonUtils.getMapping());
    //        PutMappingRequest put = Requests.putMappingRequest(search.getIndex()).type(search.getType()).source(ESJsonUtils.getMapping(search.getType()));
    //        client.admin().indices().putMapping(put).actionGet();
    //        System.out.println(search.setAlias2Index(search.getAlias(),search.getIndex()));
    //         client.prepareIndex("cms_v1", "item",programSeries.getId()+"").setSource(ESJsonUtils.getIndexJson(programSeries)).execute().actionGet();
    //        System.out.println(response.isCreated());
    //        client.delete(Requests.deleteRequest("cms_v1").type("item").id("4"));

    BoolFilterBuilder bFilter = FilterBuilders.boolFilter().must(FilterBuilders.termFilter("region_code", "a"))
            .must(FilterBuilders.termFilter("platform_code", "sanxing"))
            .must(FilterBuilders.termFilter("tag_arr.primary_tag.tag_name", ""))
            .must(FilterBuilders.termFilter("tag_arr.primary_tag.secondary_tag.primary_secondary_tag",
                    "-?"))
            .must(FilterBuilders.boolFilter().must(FilterBuilders.prefixFilter("program_series_header", "ss")));
    SearchResponse response = client.prepareSearch("icntv_cms").setTypes("item")
            .setQuery(bFilter.buildAsBytes())
            .addAggregation(AggregationBuilders.terms("first").field("tag_arr.primary_tag.tag_name")
                    .subAggregation(AggregationBuilders.terms("secondary")
                            .field("tag_arr.primary_tag.secondary_tag.primary_secondary_tag")))
            .setFrom(0).setSize(10).execute().actionGet(); //.subAggregation(AggregationBuilders.terms("secondary").field("tag_arr.primary_tag.secondary_tag.tag_name"))
    System.out.println(response.toString());
    SearchHits hits = response.getHits();
    //        System.out.println(hits.getTotalHits());
    ///*from   w  w w  . j  av a2s  .  c o m*/
    //        for(SearchHit hit:hits){

    //            System.out.println(hit.sourceAsString());
    //            ProgramSeries items= JSON.parseObject(hit.source(), ProgramSeries.class);
    //            System.out.println(JSON.toJSONString(items));
    //            System.out.println(items.getProgram_series_name() +" \t" + items.getArtist().get(0).getArtist_id());
    //            Map<String,Object> maps=hit.sourceAsMap();
    //
    //            Set<String> keys= maps.keySet();
    //            for(String str:keys){
    //                System.out.println(str+"\t"+maps.get(str));
    //            }
    //        }
    ////
    //        Terms a=response.getAggregations().get("secondary");
    ////        System.out.println(a.getName());
    //        for(Terms.Bucket b : a.getBuckets()){
    //            System.out.println(b.getKey()+"\t"+b.getDocCount());
    ////            Terms c=response.getAggregations().get("secondary");
    ////            for(Terms.Bucket x : c.getBuckets()){
    ////                System.out.println("sssssssssss "+x.getKey()+"\t"+x.getDocCount());
    ////            }
    //        }
    //        if(!Strings.isNullOrEmpty(secondary_tag)){
    //            bFilter.must(FilterBuilders.boolFilter().must(FilterBuilders.termFilter("tag_arr.primary_tag.secondary_tag.tag_name", secondary_tag)));
    //        }
    //        FilterBuilder filterBuilder = builderQuery();
    //        if(null != filterBuilder){
    //            bFilter.must(builderQuery());
    //        }

    //        client.close();
}

From source file:org.pshdl.model.types.builtIn.busses.memorymodel.MemoryModel.java

public static void main(String[] args) throws Exception {
    final File file = new File(args[0]);
    final Set<Problem> problems = Sets.newHashSet();
    final Unit unit = MemoryModelAST.parseUnit(Files.toString(file, Charsets.UTF_8), problems, 0);
    System.out.println(unit);//from   w  w  w  .ja va 2  s .com
    final List<Row> rows = buildRows(unit);
    final byte[] builtHTML = MemoryModelSideFiles.builtHTML(unit, rows, true);
    if (builtHTML == null)
        throw new IllegalArgumentException("buildHTML returned null");
    System.out.println(new BusAccess().generateAccessC(rows, true));
    System.out.println(new BusAccess().generateAccessH(unit, rows, true));
    // // SideFile[] cFiles = MemoryModelSideFiles.getCFiles(unit, rows);
    // for (SideFile sideFile : cFiles) {
    // System.out.println(sideFile.relPath);
    // System.out.println(new String(sideFile.contents));
    // }
    Files.write(builtHTML, new File(args[0] + "Map.html"));
    final HDLInterface hdi = buildHDLInterface(unit, rows);
    System.out.println(hdi);
}

From source file:org.opendaylight.netconf.test.tool.client.http.perf.RestPerfClient.java

public static void main(String[] args) throws IOException {

    Parameters parameters = parseArgs(args, Parameters.getParser());
    parameters.validate();/*from w  ww  .j a  v a2  s  .  c  o m*/
    throttle = parameters.throttle / parameters.threadAmount;

    if (parameters.async && parameters.threadAmount > 1) {
        LOG.info("Throttling per thread: {}", throttle);
    }

    final String editContentString;
    try {
        editContentString = Files.toString(parameters.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + parameters.editContent);
    }

    final int threadAmount = parameters.threadAmount;
    LOG.info("thread amount: {}", threadAmount);
    final int requestsPerThread = parameters.editCount / parameters.threadAmount;
    LOG.info("requestsPerThread: {}", requestsPerThread);
    final int leftoverRequests = parameters.editCount % parameters.threadAmount;
    LOG.info("leftoverRequests: {}", leftoverRequests);

    final ArrayList<ArrayList<DestToPayload>> allThreadsPayloads = new ArrayList<>();
    for (int i = 0; i < threadAmount; i++) {
        final ArrayList<DestToPayload> payloads = new ArrayList<>();
        for (int j = 0; j < requestsPerThread; j++) {
            final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart
                    : parameters.devicePortRangeStart + i;
            final StringBuilder destBuilder = new StringBuilder(dest);
            destBuilder.replace(destBuilder.indexOf(HOST_KEY),
                    destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip)
                    .replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(),
                            parameters.port + "");
            final StringBuilder suffixBuilder = new StringBuilder(parameters.destination);
            if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) {
                suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY),
                        suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + "");
            }
            destBuilder.append(suffixBuilder);

            payloads.add(new DestToPayload(destBuilder.toString(),
                    prepareMessage(i, j, editContentString, devicePort)));
        }
        allThreadsPayloads.add(payloads);
    }

    for (int i = 0; i < leftoverRequests; i++) {
        ArrayList<DestToPayload> payloads = allThreadsPayloads.get(allThreadsPayloads.size() - 1);

        final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart
                : parameters.devicePortRangeStart + threadAmount - 1;
        final StringBuilder destBuilder = new StringBuilder(dest);
        destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(),
                parameters.ip).replace(destBuilder.indexOf(PORT_KEY),
                        destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + "");
        final StringBuilder suffixBuilder = new StringBuilder(parameters.destination);
        if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) {
            suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY),
                    suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + "");
        }
        destBuilder.append(suffixBuilder);
        payloads.add(new DestToPayload(destBuilder.toString(),
                prepareMessage(threadAmount - 1, requestsPerThread + i, editContentString, devicePort)));
    }

    final ArrayList<PerfClientCallable> callables = new ArrayList<>();
    for (ArrayList<DestToPayload> payloads : allThreadsPayloads) {
        callables.add(new PerfClientCallable(parameters, payloads));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting performance test");
    boolean allThreadsCompleted = true;
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Void>> futures = executorService.invokeAll(callables, parameters.timeout,
                TimeUnit.MINUTES);
        for (int i = 0; i < futures.size(); i++) {
            Future<Void> future = futures.get(i);
            if (future.isCancelled()) {
                allThreadsCompleted = false;
                LOG.info("{}. thread timed out.", i + 1);
            } else {
                try {
                    future.get();
                } catch (final ExecutionException e) {
                    allThreadsCompleted = false;
                    LOG.info("{}. thread failed.", i + 1, e);
                }
            }
        }
    } catch (final InterruptedException e) {
        allThreadsCompleted = false;
        LOG.warn("Unable to execute requests", e);
    }
    executorService.shutdownNow();
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    // If some threads failed or timed out, skip calculation of requests per second value
    // and do not log it
    if (allThreadsCompleted) {
        LOG.info("Requests per second: {}",
                (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));
    }
    System.exit(0);
}

From source file:org.opendaylight.controller.netconf.test.tool.client.http.perf.RestPerfClient.java

public static void main(String[] args) throws IOException {

    Parameters parameters = parseArgs(args, Parameters.getParser());
    parameters.validate();/*from  ww  w .  j  ava2 s  .  c  o  m*/
    throttle = parameters.throttle / parameters.threadAmount;

    if (parameters.async && parameters.threadAmount > 1) {
        LOG.info("Throttling per thread: {}", throttle);
    }

    final String editContentString;
    try {
        editContentString = Files.toString(parameters.editContent, Charsets.UTF_8);
    } catch (final IOException e) {
        throw new IllegalArgumentException("Cannot read content of " + parameters.editContent);
    }

    final int threadAmount = parameters.threadAmount;
    LOG.info("thread amount: {}", threadAmount);
    final int requestsPerThread = parameters.editCount / parameters.threadAmount;
    LOG.info("requestsPerThread: {}", requestsPerThread);
    final int leftoverRequests = parameters.editCount % parameters.threadAmount;
    LOG.info("leftoverRequests: {}", leftoverRequests);

    final ArrayList<ArrayList<DestToPayload>> allThreadsPayloads = new ArrayList<>();
    for (int i = 0; i < threadAmount; i++) {
        final ArrayList<DestToPayload> payloads = new ArrayList<>();
        for (int j = 0; j < requestsPerThread; j++) {
            final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart
                    : parameters.devicePortRangeStart + i;
            final StringBuilder destBuilder = new StringBuilder(dest);
            destBuilder.replace(destBuilder.indexOf(HOST_KEY),
                    destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(), parameters.ip)
                    .replace(destBuilder.indexOf(PORT_KEY), destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(),
                            parameters.port + "");
            final StringBuilder suffixBuilder = new StringBuilder(parameters.destination);
            if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) {
                suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY),
                        suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + "");
            }
            destBuilder.append(suffixBuilder);

            payloads.add(new DestToPayload(destBuilder.toString(), prepareMessage(i, j, editContentString)));
        }
        allThreadsPayloads.add(payloads);
    }

    for (int i = 0; i < leftoverRequests; i++) {
        ArrayList<DestToPayload> payloads = allThreadsPayloads.get(allThreadsPayloads.size() - 1);

        final int devicePort = parameters.sameDevice ? parameters.devicePortRangeStart
                : parameters.devicePortRangeStart + threadAmount - 1;
        final StringBuilder destBuilder = new StringBuilder(dest);
        destBuilder.replace(destBuilder.indexOf(HOST_KEY), destBuilder.indexOf(HOST_KEY) + HOST_KEY.length(),
                parameters.ip).replace(destBuilder.indexOf(PORT_KEY),
                        destBuilder.indexOf(PORT_KEY) + PORT_KEY.length(), parameters.port + "");
        final StringBuilder suffixBuilder = new StringBuilder(parameters.destination);
        if (suffixBuilder.indexOf(DEVICE_PORT_KEY) != -1) {
            suffixBuilder.replace(suffixBuilder.indexOf(DEVICE_PORT_KEY),
                    suffixBuilder.indexOf(DEVICE_PORT_KEY) + DEVICE_PORT_KEY.length(), devicePort + "");
        }
        destBuilder.append(suffixBuilder);
        payloads.add(new DestToPayload(destBuilder.toString(),
                prepareMessage(threadAmount - 1, requestsPerThread + i, editContentString)));
    }

    final ArrayList<PerfClientCallable> callables = new ArrayList<>();
    for (ArrayList<DestToPayload> payloads : allThreadsPayloads) {
        callables.add(new PerfClientCallable(parameters, payloads));
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(threadAmount);

    LOG.info("Starting performance test");
    final Stopwatch started = Stopwatch.createStarted();
    try {
        final List<Future<Void>> futures = executorService.invokeAll(callables, 5, TimeUnit.MINUTES);
        for (final Future<Void> future : futures) {
            try {
                future.get(4L, TimeUnit.MINUTES);
            } catch (ExecutionException | TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
        executorService.shutdownNow();
    } catch (final InterruptedException e) {
        throw new RuntimeException("Unable to execute requests", e);
    }
    started.stop();

    LOG.info("FINISHED. Execution time: {}", started);
    LOG.info("Requests per second: {}",
            (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)));

    System.exit(0);
}

From source file:org.apache.curator.x.rpc.CuratorProjectionServer.java

public static void main(String[] args) throws Exception {
    if ((args.length != 1) || args[0].equalsIgnoreCase("?") || args[0].equalsIgnoreCase("-h")
            || args[0].equalsIgnoreCase("--help")) {
        printHelp();//from w  w w . j a  v  a2 s  .com
        return;
    }

    String configurationSource;
    File f = new File(args[0]);
    if (f.exists()) {
        configurationSource = Files.toString(f, Charset.defaultCharset());
    } else {
        System.out.println("First argument is not a file. Treating the command line as a json/yaml object");
        configurationSource = args[0];
    }

    final CuratorProjectionServer server = startServer(configurationSource);

    Runnable shutdown = new Runnable() {
        @Override
        public void run() {
            server.stop();
        }
    };
    Thread hook = new Thread(shutdown);
    Runtime.getRuntime().addShutdownHook(hook);
}

From source file:com.thinkbiganalytics.spark.interpreter.App.java

/**
 * Evaluates a Scala file./*  w ww .java 2s  .  com*/
 *
 * @param args the command-line arguments
 * @throws Exception if an error occurs
 */
public static void main(@Nonnull String[] args) throws Exception {
    // Verify arguments
    if (args.length != 1) {
        System.err.println("error: usage: SparkShellApp file");
        System.exit(1);
    }

    // Load environment
    final ApplicationContext ctx = new AnnotationConfigApplicationContext("com.thinkbiganalytics.spark");

    File scriptFile = new File(args[0]);
    if (scriptFile.exists() && scriptFile.isFile()) {
        log.info("Loading script file at {} ", args[0]);
    } else {
        log.info("Couldn't find script file at {} will check classpath.", args[0]);
        String fileName = scriptFile.getName();
        scriptFile = new File("./" + fileName);
    }

    final String script = Files.toString(scriptFile, Charsets.UTF_8);

    // Prepare bindings
    final List<NamedParam> bindings = new ArrayList<>();

    final DatasourceProvider datasourceProvider = ctx.getBean(DatasourceProvider.class);
    bindings.add(new NamedParamClass("datasourceProvider", datasourceProvider.getClass().getName(),
            datasourceProvider));

    // Execute script
    final SparkScriptEngine engine = ctx.getBean(SparkScriptEngine.class);
    engine.eval(script, bindings);
}

From source file:com.bouncestorage.swiftproxy.Main.java

/**
 * Main method.//w  w  w. j av a 2  s  .  c o  m
 * @param args
 */
public static void main(String[] args) throws Exception {
    if (args.length == 1 && args[0].equals("--version")) {
        System.err.println(Main.class.getPackage().getImplementationVersion());
        System.exit(0);
    } else if (args.length != 2) {
        System.err.println("Usage: swiftproxy --properties FILE");
        System.exit(1);
    }

    Properties properties = new Properties();
    try (InputStream is = new FileInputStream(new File(args[1]))) {
        properties.load(is);
    }
    properties.putAll(System.getProperties());

    String provider = properties.getProperty(Constants.PROPERTY_PROVIDER);
    String identity = properties.getProperty(Constants.PROPERTY_IDENTITY);
    String credential = properties.getProperty(Constants.PROPERTY_CREDENTIAL);
    String endpoint = properties.getProperty(Constants.PROPERTY_ENDPOINT);
    String proxyEndpoint = properties.getProperty(SwiftProxy.PROPERTY_ENDPOINT);
    if (provider == null || identity == null || credential == null || proxyEndpoint == null) {
        System.err.format("Properties file must contain:%n" + Constants.PROPERTY_PROVIDER + "%n"
                + Constants.PROPERTY_IDENTITY + "%n" + Constants.PROPERTY_CREDENTIAL + "%n"
                + SwiftProxy.PROPERTY_ENDPOINT + "%n");
        System.exit(1);
    }

    if (provider.equals("google-cloud-storage")) {
        File credentialFile = new File(credential);
        if (credentialFile.exists()) {
            credential = Files.toString(credentialFile, StandardCharsets.UTF_8);
        }
        properties.remove(Constants.PROPERTY_CREDENTIAL);
    }

    ContextBuilder builder = ContextBuilder.newBuilder(provider).credentials(identity, credential)
            .modules(ImmutableList.<Module>of(new SLF4JLoggingModule())).overrides(properties);
    if (endpoint != null) {
        builder = builder.endpoint(endpoint);
    }
    BlobStoreContext context = builder.build(BlobStoreContext.class);

    SwiftProxy proxy = SwiftProxy.Builder.builder().overrides(properties).endpoint(new URI(proxyEndpoint))
            .build();
    proxy.start();
    System.out.format("Swift proxy listening on port %d%n", proxy.getPort());
    Thread.currentThread().join();
}

From source file:org.apache.drill.exec.ref.ReferenceInterpreter.java

public static void main(String[] args) throws Exception {
    DrillConfig config = DrillConfig.create();
    final String jsonFile = args[0];
    LogicalPlan plan = LogicalPlan.parse(config, Files.toString(new File(jsonFile), Charsets.UTF_8));
    IteratorRegistry ir = new IteratorRegistry();
    ReferenceInterpreter i = new ReferenceInterpreter(plan, ir, new BasicEvaluatorFactory(ir),
            new RSERegistry(config));
    i.setup();/*from   ww w.  j av  a2  s .  c  o  m*/
    Collection<RunOutcome> outcomes = i.run();

    for (RunOutcome outcome : outcomes) {
        System.out.println("============");
        System.out.println(outcome);
        if (outcome.outcome == RunOutcome.OutcomeType.FAILED && outcome.exception != null) {
            outcome.exception.printStackTrace();
        }

    }

}

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  . java  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();
    }

}