Example usage for com.google.common.base Supplier get

List of usage examples for com.google.common.base Supplier get

Introduction

In this page you can find the example usage for com.google.common.base Supplier get.

Prototype

T get();

Source Link

Document

Retrieves an instance of the appropriate type.

Usage

From source file:cl.whyem.testsutilityproject.otpgenerator.OtpExample.java

public static void main(String... args) throws Exception {

    // the time-based one-time-password uses time as the 
    // moving factor. so long as two parties have the same
    // source key and synchronize their clocks, they will
    // be able to generate the same one-time-password for 
    // the same window of time (in this example, the window
    // changes every 30 seconds). 

    // OTP generators are immutable and threadsafe.

    byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

    Otp.Totp totp = new Otp.Totp(60, key);

    System.out.println(totp.generateNext());

    // We can also use the Guava libraries supplier interface...

    Supplier<String> otp = Otp.totpSupplier(key, 30);
    System.out.println(otp.get());

    // Use your own OTP if you'd like...    
    otp = Otp.supplier(new MyOtp(key));
    System.out.println(otp.get()); // with this one,
    System.out.println(otp.get()); // the otp changes
    System.out.println(otp.get()); // every call because
    System.out.println(otp.get()); // of the counter

}

From source file:org.jclouds.examples.google.lb.MainApp.java

public static void main(String[] args) {
    if (args.length < PARAMETERS)
        throw new IllegalArgumentException(INVALID_SYNTAX);

    String jsonKeyFile = args[0];
    Action action = Action.valueOf(args[1].toUpperCase());

    // Read in JSON key.
    String fileContents = null;/*from  ww  w  . jav a2  s  .  c  o m*/
    try {
        fileContents = Files.toString(new File(jsonKeyFile), Charset.defaultCharset());
    } catch (IOException ex) {
        System.out.println("Error Reading the Json key file. Please check the provided path is correct.");
        System.exit(1);
    }

    Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);

    // This demonstrates how to initialize a ComputeServiceContext using json key files.
    ComputeServiceContext context = ContextBuilder.newBuilder("google-compute-engine")
            .credentialsSupplier(credentialSupplier).buildView(ComputeServiceContext.class);

    Credentials credentials = credentialSupplier.get();

    GoogleComputeEngineApi googleApi = createGoogleComputeEngineApi(credentials.identity,
            credentials.credential);

    String project_name = googleApi.project().get().name();
    System.out.printf("Sucessfully Authenticated to project %s\n", project_name);

    InstanceApi instanceApi = googleApi.instancesInZone(DEFAULT_ZONE);

    switch (action) {
    case CREATE: {
        Metadata metadata = googleApi.project().get().commonInstanceMetadata();
        if (metadata.get("startup-script") != null && metadata.get("startup-script") != STARTUP_SCRIPT) {

            System.out.println("Project already has a startup script, exiting to avoid overwriting it.");
            System.exit(1);
        }
        System.out.println("Updating startup script");
        metadata.put("startup-script", STARTUP_SCRIPT);
        Operation operation = googleApi.project().setCommonInstanceMetadata(metadata);
        OperationApi operationsApi = googleApi.operations();
        WaitForOperation(operationsApi, operation);

        URI networkURL = googleApi.networks().get("default").selfLink();
        if (networkURL == null) {
            System.out.println(
                    "Your project does not have a default network. Please recreate the default network or try again with a new project");
            System.exit(1);
        }
        System.out.println("Creating:");

        // Add firewall rule to allow TCP on port 80
        FirewallOptions options = new FirewallOptions()
                .addAllowedRule(Firewall.Rule.create("tcp", ImmutableList.of("80")))
                .sourceRanges(ImmutableList.of("0.0.0.0/0"));
        //.addTargetTag(FIREWALL_TAG);
        operation = googleApi.firewalls().createInNetwork("jclouds-lb-firewall-tcp-80", networkURL, options);
        System.out.println(" - firewall");
        WaitForOperation(operationsApi, operation);

        URI machineTypeURL = googleApi.machineTypesInZone(DEFAULT_ZONE).get(DEFAULT_MACHINE_TYPE).selfLink();

        // Make requests to create instances.
        ArrayList<Operation> operations = new ArrayList<Operation>();
        for (int i = 0; i < NUM_INSTANCES; i++) {
            Operation o = instanceApi.create(NewInstance.create("jclouds-lb-instance-" + i, machineTypeURL,
                    networkURL, DEFAULT_IMAGE_URL));
            System.out.println(" - instance");
            operations.add(o);
        }

        ArrayList<URI> instances = new ArrayList<URI>();
        for (Operation op : operations) {
            WaitForOperation(operationsApi, op);
            instances.add(op.targetLink());
        }

        // Create Health Check
        HttpHealthCheckCreationOptions healthCheckOptions = new HttpHealthCheckCreationOptions.Builder()
                .checkIntervalSec(1).timeoutSec(1).buildWithDefaults();
        operation = googleApi.httpHeathChecks().insert("jclouds-lb-healthcheck", healthCheckOptions);
        System.out.println(" - http health check");
        WaitForOperation(operationsApi, operation);
        URI healthCheckURI = googleApi.httpHeathChecks().get("jclouds-lb-healthcheck").selfLink();

        // Create Target Pool
        TargetPoolCreationOptions targetPoolOptions = new TargetPoolCreationOptions.Builder(
                "jclouds-lb-target-pool").healthChecks(ImmutableList.of(healthCheckURI)).instances(instances)
                        .build();
        Operation targetPoolOperation = googleApi.targetPoolsInRegion(DEFAULT_REGION).create(targetPoolOptions);
        System.out.println(" - target pool");
        WaitForOperation(operationsApi, targetPoolOperation);

        // Create Forwarding Rule
        ForwardingRuleCreationOptions forwardingOptions = new ForwardingRuleCreationOptions.Builder()
                .ipProtocol(ForwardingRule.IPProtocol.TCP).target(targetPoolOperation.targetLink()).build();
        operation = googleApi.forwardingRulesInRegion(DEFAULT_REGION).create("jclouds-lb-forwarding",
                forwardingOptions);
        System.out.println(" - forwarding rule");
        WaitForOperation(operationsApi, operation);

        String ipAddress = googleApi.forwardingRulesInRegion(DEFAULT_REGION).get("jclouds-lb-forwarding")
                .ipAddress();
        System.out.println("Ready to recieve traffic at " + ipAddress);

        break;
    }
    case REQUEST: {
        // Find the created forwarding rule.
        ForwardingRule forwardingRule = googleApi.forwardingRulesInRegion(DEFAULT_REGION)
                .get("jclouds-lb-forwarding");
        if (forwardingRule == null) {
            System.out.println("jclouds-lb-forwarding rule does not exist. Have you successfully run create?");
            System.exit(1);
        }
        String ipAddress = googleApi.forwardingRulesInRegion(DEFAULT_REGION).get("jclouds-lb-forwarding")
                .ipAddress();
        System.out.printf("Found the forwarding rule! Try executing 'while true; do curl -m1 %s; done'\n",
                ipAddress);

        break;
    }
    case DELETE_STARTUP_SCRIPT: {
        System.out.println("removing startup script from project metadata");
        DeleteStartupScript(googleApi);
        break;
    }
    case DESTROY: {
        // Delete Forwarding Rule
        googleApi.forwardingRulesInRegion(DEFAULT_REGION).delete("jclouds-lb-forwarding");

        // Delete Target Pool
        googleApi.targetPoolsInRegion(DEFAULT_REGION).delete("jclouds-lb-target-pool");

        // Delete Health Check
        googleApi.httpHeathChecks().delete("jclouds-lb-healthcheck");

        // Delete Instances
        ArrayList<Operation> operations = new ArrayList<Operation>();
        for (int i = 0; i < NUM_INSTANCES; i++) {
            Operation o = instanceApi.delete("jclouds-lb-instance-" + i);
            operations.add(o);
        }

        // Delete Firewall Rule
        googleApi.firewalls().delete("jclouds-lb-firewall-tcp-80");

        // Delete Startup Script
        DeleteStartupScript(googleApi);

        System.out.println("ran cleanup");
        break;
    }
    }
}

From source file:com.github.filosganga.geogson.util.ChainableOptional.java

public static <T> ChainableOptional<T> of(Supplier<Optional<? extends T>> src) {
    return of(src.get());
}

From source file:see.reactive.impl.DynamicDependenciesSignal.java

public static <T> DynamicDependenciesSignal<T> create(Supplier<EvaluationResult<T>> evaluation) {
    EvaluationResult<T> result = evaluation.get();
    return new DynamicDependenciesSignal<T>(evaluation, checkDependencies(result.getDependencies()),
            result.getResult());/*ww  w  .j  ava2 s  . c o  m*/
}

From source file:com.google.api.control.model.ValidationException.java

private static String message(Stack<Supplier<String>> context, String format, Object... args) {
    if (context == null || context.isEmpty()) {
        return String.format(format, args);
    }//from   w ww.  jav  a 2s  . c  o  m
    StringBuilder result = new StringBuilder();
    for (Supplier<String> supplier : context) {
        result.append(supplier.get() + ": ");
    }
    return result.toString() + String.format(format, args);
}

From source file:io.mesosphere.mesos.util.Functions.java

@NotNull
public static <A> List<A> listFullOf(final int capacity, @NotNull final Supplier<A> sup) {
    final A value = sup.get();
    final List<A> list = new ArrayList<>(capacity);
    for (int i = 0; i < capacity; i++) {
        list.add(value);//w  w  w.j  ava  2 s.  c o  m
    }
    return list;
}

From source file:iterator.util.Utils.java

public static <T> T waitFor(final Predicate<T> predicate, final Supplier<T> input) {
    for (int spin = 0; Predicates.not(predicate).apply(input.get());) {
        if (++spin % 10_000_000 == 0)
            System.err.print('.');
    }/* w  w w  . java2  s .c o  m*/
    T result = input.get();
    System.err.println(result.getClass().getName());
    return result;
}

From source file:org.jclouds.util.Assertions.java

public static boolean eventuallyTrue(Supplier<Boolean> assertion, long inconsistencyMillis)
        throws InterruptedException {

    for (int i = 0; i < 30; i++) {
        if (!assertion.get()) {
            Thread.sleep(inconsistencyMillis / 30);
            continue;
        }//  w  ww  . jav a 2  s.c om
        return true;
    }
    return false;
}

From source file:com.palantir.common.supplier.ServiceContexts.java

public static <T> ServiceContext<T> fromSupplier(final Supplier<? extends T> supplier) {
    return new ServiceContext<T>() {
        @Override/*from  w w w  .j  av  a  2s .c o  m*/
        public T get() {
            return supplier.get();
        }

        @Override
        public <R> R callWithContext(T context, java.util.concurrent.Callable<R> callable) throws Exception {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.apache.brooklyn.entity.software.base.test.mysql.DynamicToyMySqlEntityBuilder.java

private static boolean isLocalhost(Supplier<MachineLocation> machineS) {
    return machineS.get() instanceof LocalhostMachine;
}