Example usage for com.google.common.base Suppliers ofInstance

List of usage examples for com.google.common.base Suppliers ofInstance

Introduction

In this page you can find the example usage for com.google.common.base Suppliers ofInstance.

Prototype

public static <T> Supplier<T> ofInstance(@Nullable T instance) 

Source Link

Document

Returns a supplier that always supplies instance .

Usage

From source file:com.google.cloud.genomics.api.client.GenomicsSample.java

public static void main(String[] args) throws IOException {
    CommandLine cmdLine = new CommandLine();

    try {/*from   ww w .ja  va  2  s  .c  o  m*/
        // Parse the command line
        cmdLine.setArgs(args);

        // Authorization
        BaseCommand command = cmdLine.getCommand();
        List<String> scopes = command.getScopes();
        VerificationCodeReceiver receiver = command.noLocalServer ? new GooglePromptReceiver()
                : new LocalServerReceiver();

        GenomicsFactory genomicsFactory = GenomicsFactory.builder("genomics_java_client").setScopes(scopes)
                .setUserName("user" + scopes.toString())
                .setVerificationCodeReceiver(Suppliers.ofInstance(receiver)).setRootUrl(command.rootUrl)
                .setServicePath("/").build();

        File clientSecrets = new File(command.clientSecretsFilename);
        if (!clientSecrets.exists()) {
            System.err.println("Client secrets file " + command.clientSecretsFilename + " does not exist."
                    + " Visit https://cloud.google.com/genomics/install-genomics-tools#authenticate to learn how"
                    + " to install a client_secrets.json file.  If you have installed a client_secrets.json"
                    + " in a specific location, use --client_secrets_filename <path>/client_secrets.json.");
            return;
        }

        File dataStoreFile = new File(System.getProperty("user.home"), ".store/genomics_java_client");
        command.setDataStoreFactory(new ReadableFileDataStoreFactory(dataStoreFile));
        command.handleRequest(genomicsFactory.fromClientSecretsFile(clientSecrets));

    } catch (IllegalArgumentException | ParameterException e) {
        cmdLine.printHelp(e.getMessage() + "\n", System.out);
    } catch (GoogleJsonResponseException e) {
        System.out.println("API request failed: " + BaseCommand.getErrorMessage(e));
    } catch (IllegalStateException e) {
        System.out.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.google.cloud.genomics.gettingstarted.MainExample.java

public static void main(String[] args) throws IOException {
    Arguments arguments = new Arguments();
    JCommander parser = new JCommander(arguments);

    try {/*from  ww w .  j a v  a  2s.  c o  m*/
        // Parse the command line
        parser.parse(args);

        // Authorization
        VerificationCodeReceiver receiver = arguments.noLocalServer ? new GooglePromptReceiver()
                : new LocalServerReceiver();
        GenomicsFactory genomicsFactory = GenomicsFactory.builder("getting_started_java")
                .setScopes(Lists.newArrayList(GenomicsScopes.GENOMICS))
                .setVerificationCodeReceiver(Suppliers.ofInstance(receiver)).build();

        File clientSecrets = new File(arguments.clientSecretsFilename);
        if (!clientSecrets.exists()) {
            System.err.println("Client secrets file " + arguments.clientSecretsFilename + " does not exist."
                    + " Visit https://cloud.google.com/genomics/install-genomics-tools#authenticate to learn how"
                    + " to install a client_secrets.json file.  If you have installed a client_secrets.json"
                    + " in a specific location, use --client_secrets_filename <path>/client_secrets.json.");
            return;
        }
        Genomics genomics = genomicsFactory.fromClientSecretsFile(clientSecrets);

        //
        // This example gets the read bases for a sample at specific a position
        //
        String datasetId = "10473108253681171589"; // This is the 1000 Genomes dataset ID
        String sample = "NA12872";
        String referenceName = "22";
        final Long referencePosition = 51003835L;

        // 1. First find the read group set ID for the sample
        SearchReadGroupSetsRequest readsetsReq = new SearchReadGroupSetsRequest()
                .setDatasetIds(Lists.newArrayList(datasetId)).setName(sample);

        List<ReadGroupSet> readGroupSets = genomics.readgroupsets().search(readsetsReq)
                .setFields("readGroupSets(id)").execute().getReadGroupSets();
        if (readGroupSets == null || readGroupSets.size() != 1) {
            System.err
                    .println("Searching for " + sample + " didn't return the right number of read group sets");
            return;
        }

        String readGroupSetId = readGroupSets.get(0).getId();

        // 2. Once we have the read group set ID,
        // lookup the reads at the position we are interested in
        SearchReadsRequest readsReq = new SearchReadsRequest()
                .setReadGroupSetIds(Lists.newArrayList(readGroupSetId)).setReferenceName(referenceName)
                .setStart(referencePosition).setEnd(referencePosition + 1);

        List<Read> reads = genomics.reads().search(readsReq).setFields("alignments(alignment,alignedSequence)")
                .execute().getAlignments();

        Map<Character, Integer> baseCounts = Maps.newHashMap();
        for (Read read : reads) {
            int index = (int) (referencePosition - read.getAlignment().getPosition().getPosition());

            // Note: This is simplistic - the cigar should be considered for real code
            Character base = read.getAlignedSequence().charAt(index);

            if (!baseCounts.containsKey(base)) {
                baseCounts.put(base, 0);
            }
            baseCounts.put(base, baseCounts.get(base) + 1);
        }

        System.out.println(sample + " bases on " + referenceName + " at " + referencePosition + " are");
        for (Map.Entry<Character, Integer> entry : baseCounts.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }

        //
        // This example gets the variants for a sample at a specific position
        //

        // 1. First find the call set ID for the sample
        SearchCallSetsRequest callSetsReq = new SearchCallSetsRequest()
                .setVariantSetIds(Lists.newArrayList(datasetId)).setName(sample);

        List<CallSet> callSets = genomics.callsets().search(callSetsReq).setFields("callSets(id)").execute()
                .getCallSets();
        if (callSets == null || callSets.size() != 1) {
            System.err.println("Searching for " + sample + " didn't return the right number of call sets");
            return;
        }

        String callSetId = callSets.get(0).getId();

        // 2. Once we have the call set ID,
        // lookup the variants that overlap the position we are interested in
        SearchVariantsRequest variantsReq = new SearchVariantsRequest()
                .setCallSetIds(Lists.newArrayList(callSetId)).setReferenceName(referenceName)
                .setStart(referencePosition).setEnd(referencePosition + 1);

        Variant variant = genomics.variants().search(variantsReq)
                .setFields("variants(names,referenceBases,alternateBases,calls(genotype))").execute()
                .getVariants().get(0);

        String variantName = variant.getNames().get(0);

        List<String> genotype = Lists.newArrayList();
        for (Integer g : variant.getCalls().get(0).getGenotype()) {
            if (g == 0) {
                genotype.add(variant.getReferenceBases());
            } else {
                genotype.add(variant.getAlternateBases().get(g - 1));
            }
        }

        System.out.println("the called genotype is " + Joiner.on(',').join(genotype) + " at " + variantName);

    } catch (ParameterException e) {
        System.err.append(e.getMessage()).append("\n");
        parser.usage();
    } catch (IllegalStateException e) {
        System.err.println(e.getMessage());
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.netflix.astyanax.connectionpool.impl.Stress.java

/**
 * @param args//  w w w . j  a  v  a 2s  .c  o m
 */
public static void main(String[] args) {
    ConnectionPoolConfigurationImpl config;
    config = new ConnectionPoolConfigurationImpl(
            TestConstants.CLUSTER_NAME + "_" + TestConstants.KEYSPACE_NAME);
    //        config.setMaxConns(100);
    config.setMaxFailoverCount(-1);
    config.setMaxTimeoutWhenExhausted(1000);
    config.setMaxConnsPerHost(25);
    config.setInitConnsPerHost(0);
    config.setTimeoutWindow(5000);
    config.setMaxTimeoutCount(10);
    config.setRetrySuspendWindow(5000);
    config.setLatencyScoreStrategy(new EmaLatencyScoreStrategyImpl(1000, 0, 20));
    // config.setRetryBackoffStrategy(new
    // ExponentialRetryBackoffStrategy(20, 1000, 2000));

    final ConnectionPoolMonitor monitor = new CountingConnectionPoolMonitor();
    TestConnectionFactory factory = new TestConnectionFactory(config, monitor);
    final ConnectionPool<TestClient> pool = new RoundRobinConnectionPoolImpl<TestClient>(config, factory,
            monitor);
    pool.start();

    final List<Host> hosts = Lists.newArrayList(new Host("127.0.0.1", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.2", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.3", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.4", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.5", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.6", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.7", TestHostType.GOOD_FAST.ordinal()),
            new Host("127.0.0.8", TestHostType.GOOD_FAST.ordinal()),
            //                new Host("127.0.0.9",  TestHostType.GOOD_SLOW.ordinal()),
            new Host("127.0.0.10", TestHostType.SWAP_EVERY_200.ordinal()),
            new Host("127.0.0.11", TestHostType.ALTERNATING_SOCKET_TIMEOUT_200.ordinal())
    //                new Host("127.0.0.12", TestHostType.ALTERNATING_SOCKET_TIMEOUT_200.ordinal()),
    //                new Host("127.0.0.13",  TestHostType.CONNECT_FAIL_FIRST_TWO.ordinal())
    );

    for (Host host : hosts) {
        pool.addHost(host, true);
    }

    final Map<Host, AtomicLong> counts = new TreeMap<Host, AtomicLong>();
    for (HostConnectionPool<TestClient> p : pool.getActivePools()) {
        counts.put(p.getHost(), new AtomicLong());
    }
    System.out.println(monitor.toString());

    final AtomicBoolean timeoutsEnabled = new AtomicBoolean(false);
    final AtomicLong lastOperationCount = new AtomicLong();

    EmaLatencyScoreStrategyImpl latency = new EmaLatencyScoreStrategyImpl(1000, 0, 10);
    final Instance sampler = latency.createInstance();
    latency.start(new Listener() {
        @Override
        public void onUpdate() {
        }

        @Override
        public void onReset() {
        }
    });
    final Function<TestDriver, Void> function = new ProbabalisticFunction.Builder<TestDriver, Void>()
            .withDefault(new Function<TestDriver, Void>() {
                public Void apply(TestDriver arg0) {
                    return null;
                }
            }).withAlways(new Runnable() {
                public void run() {
                    think(10, 30);
                }
            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    if (timeoutsEnabled.get()) {
            //                        think(1100, 0);
            //                        throw new RuntimeException(new TimeoutException("TimeoutException"));
            //                    }
            //                    return null;
            //                }
            //            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    throw new RuntimeException(new UnknownException(new Exception("UnknownExceptionDescription")));
            //                }
            //            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    think(1000, 0);
            //                    throw new RuntimeException(new OperationTimeoutException("OperationTimeoutException"));
            //                }
            //            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    throw new RuntimeException(new HostDownException("HostDownException"));
            //                }
            //            })
            //            .withProbability(0.01, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    throw new RuntimeException(new ConnectionAbortedException("ConnectionAbortedException"));
            //                }
            //            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    throw new RuntimeException(new BadRequestException("BadRequestException"));
            //                }
            //            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    throw new RuntimeException(new TokenRangeOfflineException("TokenRangeOfflineException"));
            //                }
            //            })
            //            .withProbability(0.0001, new Function<TestDriver, Void>() {
            //                public Void apply(@Nullable TestDriver arg0) {
            //                    throw new RuntimeException(new TransportException("TransportException"));
            //                }
            //            })
            .build();

    final List<HostConnectionPool<TestClient>> hostPools = Lists.newArrayList(pool.getActivePools());

    final TestDriver driver = new TestDriver.Builder().withIterationCount(0).withThreadCount(200)
            //            .withFutures(100,  TimeUnit.MILLISECONDS)
            .withCallsPerSecondSupplier(Suppliers.ofInstance(200))
            //            .withFutures(100, TimeUnit.MILLISECONDS)
            .withCallback(new Function<TestDriver, Void>() {
                public Void apply(final TestDriver driver) {
                    long startTime = System.nanoTime();
                    try {
                        pool.executeWithFailover(new TestOperation() {
                            public String execute(TestClient client)
                                    throws ConnectionException, OperationException {
                                try {
                                    function.apply(driver);
                                    return null;
                                } catch (RuntimeException e) {
                                    if (e.getCause() instanceof ConnectionException)
                                        throw (ConnectionException) e.getCause();
                                    throw e;
                                }
                            }
                        }, new RunOnce());
                    } catch (PoolTimeoutException e) {
                        LOG.info(e.getMessage());
                    } catch (ConnectionException e) {
                    } finally {
                        sampler.addSample((System.nanoTime() - startTime) / 1000000);
                    }

                    return null;
                }
            })

            // 
            //  Event to turn timeouts on/off
            //
            .withRecurringEvent(10, TimeUnit.SECONDS, new Function<TestDriver, Void>() {
                @Override
                public Void apply(TestDriver driver) {
                    timeoutsEnabled.getAndSet(!timeoutsEnabled.get());
                    //                    LOG.info("Toggle timeouts " + timeoutsEnabled.get());
                    return null;
                }
            })

            //
            //  Print status information
            //
            .withRecurringEvent(1, TimeUnit.SECONDS, new Function<TestDriver, Void>() {
                @Override
                public Void apply(TestDriver driver) {
                    long opCount = lastOperationCount.get();
                    lastOperationCount.set(driver.getOperationCount());

                    System.out.println("" + driver.getRuntime() + "," + sampler.getScore() + ","
                            + (lastOperationCount.get() - opCount));
                    System.out.println(monitor.toString());
                    System.out.println(monitor.toString());
                    for (HostConnectionPool<TestClient> host : pool.getPools()) {
                        System.out.println("   " + host.toString());
                    }
                    return null;
                }
            })

            //
            //  Remove a random host
            //
            .withRecurringEvent(10, TimeUnit.SECONDS, new Function<TestDriver, Void>() {
                @Override
                public Void apply(TestDriver driver) {
                    //                    System.out.println("Latency: " + sampler.getScore());
                    //                    
                    //                    List<Host> newHosts = Lists.newArrayList(hosts);
                    //                    newHosts.remove(new Random().nextInt(hosts.size()));
                    //                    pool.setHosts(newHosts);
                    //                    
                    //                    System.out.println(monitor.toString());
                    //                    for (HostConnectionPool<TestClient> host : pool.getPools()) {
                    //                        System.out.println("   " + host.toString());
                    //                    }
                    return null;
                }
            }).build();

    driver.start();
    try {
        driver.await();
    } catch (InterruptedException e) {
    }
}

From source file:com.pipeline.container.BufferedMemoryContainer.java

private static Supplier<ByteBuffer> createBuffer(int size) {
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(size);
    return Suppliers.ofInstance(byteBuffer);
}

From source file:org.jabylon.common.util.config.DynamicConfigUtil.java

private static synchronized void createSuppliers() {
    configTabs = Suppliers.memoize(Suppliers.compose(new IConfigurationElementLoader(),
            Suppliers.ofInstance("org.jabylon.rest.ui.configTab")));
    configSections = Suppliers.memoize(Suppliers.compose(new IConfigurationElementLoader(),
            Suppliers.ofInstance("org.jabylon.rest.ui.config")));

}

From source file:org.apache.beam.sdk.io.AvroUtils.java

/** Helper to get around the fact that {@link Schema} itself is not serializable. */
public static Supplier<Schema> serializableSchemaSupplier(String jsonSchema) {
    return Suppliers.memoize(Suppliers.compose(new JsonToSchema(), Suppliers.ofInstance(jsonSchema)));
}

From source file:com.bitranger.parknshop.common.recommend.util.MoreSuppliers.java

public static <X, T> Supplier<T> curry(Function<? super X, T> func, X arg) {
    return Suppliers.compose(func, Suppliers.ofInstance(arg));
}

From source file:com.palantir.common.proxy.DelayProxy.java

public static <T> T newProxyInstance(Class<T> interfaceClass, T delegate, long sleepTimeMs) {
    return newProxyInstance(interfaceClass, delegate, Suppliers.ofInstance(sleepTimeMs));
}

From source file:com.github.ykrasik.jerminal.internal.command.parameter.ParamUtils.java

/**
 * @param value Value to be returned by the created {@link Supplier}.
 * @param <T> Supplier type.//from   w  ww .  j a v a  2 s.co m
 * @return A {@link Supplier} that always returns the value.
 */
public static <T> Supplier<T> constValueSupplier(T value) {
    return Suppliers.ofInstance(Objects.requireNonNull(value));
}

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

public static <T> ServiceContext<T> ofInstance(final T t) {
    return fromSupplier(Suppliers.ofInstance(t));
}