Example usage for com.google.common.base Function apply

List of usage examples for com.google.common.base Function apply

Introduction

In this page you can find the example usage for com.google.common.base Function apply.

Prototype

@Nullable
T apply(@Nullable F input);

Source Link

Document

Returns the result of applying this function to input .

Usage

From source file:org.apache.abdera2.examples.simple.Parse.java

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

    Parser parser = Abdera.getInstance().getParser();

    InputStream in = Parse.class.getResourceAsStream("/simple.xml");
    Document<Feed> doc = parser.parse(in);
    Feed feed = doc.getRoot();/*w  w  w . j  a  va  2s  .  c o m*/

    System.out.println(feed.getTitle());
    System.out.println(feed.getTitleType());
    System.out.println(feed.getAlternateLink().getResolvedHref());
    System.out.println(feed.getUpdated());
    System.out.println(feed.getAuthor().getName());
    System.out.println(feed.getId());

    Entry entry = feed.getEntries().get(0);

    System.out.println(entry.getTitle());
    System.out.println(entry.getTitleType());
    System.out.println(entry.getAlternateLink().getHref()); // relative URI
    System.out.println(entry.getAlternateLink().getResolvedHref()); // absolute URI resolved against Base URI
    System.out.println(entry.getId());
    System.out.println(entry.getUpdated());
    System.out.println(entry.getSummary());
    System.out.println(entry.getSummaryType());

    // Selectors can be used to filter out unwanted entries
    List<Entry> entries = feed.getEntries(Selectors.updated(DateTimes.afterNow()));
    System.out.println(entries);

    // We can also use the Guava (com.google.common.*) Function interface
    in = Parse.class.getResourceAsStream("/simple.xml");
    Function<InputStream, Document<Feed>> pf = Parsers.forInputStream();
    doc = pf.apply(in);

    // Which means we can chain things together in interesting ways...
    in = Parse.class.getResourceAsStream("/simple.xml");
    pf = Parsers.forInputStream();
    WriterFunction wf = Writers.forOutputStream("activity", System.out);
    Function<InputStream, Void> f = Functions.compose(wf, pf);
    f.apply(in);
}

From source file:eu.thebluemountain.customers.dctm.brownbag.badcontentslister.Main.java

public static void main(String[] args) {
    try {/*from www.j a  va2 s .  co  m*/
        Map<Command, Optional<String>> cmds = Command.parse(args);
        if ((cmds.containsKey(Command.HELP)) || (!cmds.containsKey(Command.CONFIG))) {
            usage();
            return;
        }
        final JDBCConfig config = config(cmds.get(Command.CONFIG).get());

        String pwd = config.password.orNull();
        if (null == pwd) {
            Optional<String> opt = passwordOf("database", config.user);
            if (!opt.isPresent()) {
                throw new ExitException(RetCode.ERR_CANCELLED);
            }
            pwd = opt.get();
        }
        try (JDBCConnection from = create(config, pwd); CSVWriter writer = makeLog(config.user)) {
            Stopwatch watch = Stopwatch.createStarted();
            Stores stores = StoresReader.STORESREADER.apply(from);
            System.out.println("spent " + watch.stop() + " to load stores");
            final Function<DecoratedContent, Checks.Result> checker = Checks.checker(stores);
            final Multiset<Checks.Code> codes = TreeMultiset.create();
            watch.reset().start();
            ResponseUI rui = ResponseUI.create(1024, 64);
            try (CloseableIterator<DecoratedContent> it = DCReader.reader(from, stores)) {
                long count = 0L;
                while (it.hasNext()) {
                    DecoratedContent dc = it.next();
                    count++;
                    final Checks.Result result = checker.apply(dc);
                    assert null != result;
                    rui.onResponse(result);
                    final Checks.Code code = result.code;
                    codes.add(code);
                    if (code != Checks.Code.OK) {
                        // we've got an error then ....
                        writer.writeError(dc, result);
                    }
                }
                rui.finish();
                System.out.println("spent " + watch.stop() + " to read " + count + " d.c.");
                System.out.println("stats: " + codes);
                System.out.println("bye");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.err);
        System.err.flush();
        System.out.println();
        usage();
        System.exit(RetCode.ERR_SQL.ordinal());
    } catch (ExitException e) {
        e.exit();
    } catch (RuntimeException | IOException e) {
        e.printStackTrace(System.err);
        System.err.flush();
        System.out.println();
        usage();
        System.exit(RetCode.ERR_OTHER.ordinal());
    }
}

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

/**
 * @param args//from w  w  w .  j  a v  a  2  s. 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.emftriple.util.Functions.java

public static <E, T> T transform(E from, Function<E, T> function) {
    return function.apply(from);
}

From source file:com.facebook.buck.util.MoreFunctions.java

/**
 * @param arg argument to apply./*from w ww  .j  a v  a2  s  .  co  m*/
 * @param <A> argument type.
 * @param <V> result type.
 * @return a function that applies arg to a function it receives as input.
 */
public static final <A, V> Function<Function<A, V>, V> applyFunction(final A arg) {
    return new Function<Function<A, V>, V>() {
        @Override
        public V apply(Function<A, V> input) {
            return input.apply(arg);
        }
    };
}

From source file:com.yammer.collections.transforming.TransformationUtil.java

static <F, T> T safeTransform(F from, Function<F, T> conversionFunction) {
    return from == null ? null : conversionFunction.apply(from);
}

From source file:com.samskivert.depot.impl.operator.BaseOperator.java

public static <S, T extends Comparable<T>> int compare(Function<S, T> fun, S lhs, S rhs) {
    return fun.apply(lhs).compareTo(fun.apply(rhs));
}

From source file:org.blockartistry.mod.ThermalRecycling.util.function.Apply.java

public static <T, O> void forEach(final T[] list, final Function<T, O> func) {
    for (final T e : list)
        func.apply(e);
}

From source file:org.blockartistry.mod.ThermalRecycling.util.function.Apply.java

public static <T, O> Iterable<T> forEach(final Iterable<T> iterable, final Function<T, O> func) {
    for (final T e : iterable)
        func.apply(e);
    return iterable;
}

From source file:com.google.errorprone.internal.NonDelegatingClassLoaderRunner.java

public static <T, R> R run(T input, Class<R> outClass, String runnerClassName) {
    ClassLoader loader = NonDelegatingClassLoader.create(ImmutableSet.<String>of(Function.class.getName()));
    try {/*from   www.  j  a va 2 s .c o m*/
        Class<?> runnerClass = Class.forName(runnerClassName, true, loader);
        Function<T, R> runner = Function.class.cast(runnerClass.newInstance());
        return runner.apply(input);
    } catch (ReflectiveOperationException e) {
        throw new LinkageError("Unable to create runner.", e);
    }
}