Example usage for com.google.common.reflect TypeToken of

List of usage examples for com.google.common.reflect TypeToken of

Introduction

In this page you can find the example usage for com.google.common.reflect TypeToken of.

Prototype

public static TypeToken<?> of(Type type) 

Source Link

Document

Returns an instance of type token that wraps type .

Usage

From source file:com.amitinside.java8.practice.guava.reflection.Reflection.java

public static void main(final String[] args) throws NoSuchMethodException, SecurityException {
    final List<String> stringList = Lists.newArrayList();
    final List<Integer> intList = Lists.newArrayList();
    System.out.println(stringList.getClass().isAssignableFrom(intList.getClass()));
    // returns true, even though ArrayList<String> is not assignable from
    // ArrayList<Integer>

    TypeToken.of(String.class);
    TypeToken.of(Integer.class);
    final TypeToken<List<String>> stringListTok = new TypeToken<List<String>>() {

    };/*w w w.  j a  v  a2s .c  o m*/
    final TypeToken<List<Integer>> integerListTok = new TypeToken<List<Integer>>() {
    };
    System.out.println(stringListTok.isSupertypeOf(integerListTok));
    final Candidate candidate = new Candidate("AMIT");
    final Method getMethod = Arrays.stream(candidate.getClass().getMethods())
            .filter(method -> method.isAnnotationPresent(Nullable.class)).findFirst().get();
    final Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {
    }.method(getMethod);
    System.out.println(invokable.isStatic());

}

From source file:com.ondeck.datapipes.examples.SimpleFlowExample.java

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

    /**//ww w .j a v  a 2 s. c  om
     * A Dataprovider step is required to provide input to a Flow
     */
    DataProviderStep<String> dataProviderStep = new DataProviderStep<>(TypeToken.of(String.class));

    /**
     * Step one is a FunctionStep that takes a String argument and converts it into an Integer.
     * The parent of this step is the dataProviderStep.
     */
    FunctionStep<String, Integer> stepOne = new FunctionStep<>(new Function<String, Integer>() {
        @Override
        public Integer apply(String sourceValue) {
            List<Integer> list = Lists.newArrayList();
            list.add(Integer.valueOf(sourceValue));
            System.out.println("Step One : Input string is " + sourceValue + ". Converting to int.");
            return Integer.valueOf(sourceValue);
        }
    }, dataProviderStep, TypeToken.of(Integer.class));

    /**
     * Step two is a FunctionStep that takes the result of step one and multiplies it by two.
     */
    FunctionStep<Integer, Integer> stepTwo = new FunctionStep<>(new Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer sourceValue) {
            System.out.println("Step Two : Multiplying input by 2");
            return sourceValue * 2;
        }
    }, stepOne, TypeToken.of(Integer.class));

    /**
     * Finally use an executor to execute the flow.
     */
    String[] inputs = new String[] { "1", "50", "12" };
    for (String i : inputs) {
        SimpleExecuteVisitor<Integer> executeVisitor = new SimpleExecuteVisitor<>();
        executeVisitor.addInput(new TypeToken<String>() {
        }, i);
        Integer result = executeVisitor.execute(stepTwo);
        System.out.println("Result is " + result);
        System.out.println();
    }
}

From source file:com.ondeck.datapipes.examples.SimpleFlowConditionalStepExample.java

public static void main(String[] args) throws FlowException {
    /**//from   w w w .j a va2  s  .c  om
     * oddResultProvider and evenResultProvider are DataProvider steps providing Strings. DataProviderStep are meant
     * to indicate that the data returned by this type of step is provided as an input of the flow.
     */
    DataProviderStep<String> oddResultProvider = new DataProviderStep<>(TypeToken.of(String.class));
    DataProviderStep<String> evenResultProvider = new DataProviderStep<>(TypeToken.of(String.class));
    /**
     * Naming the step since we will be adding 2 String DataProviders to the input of the ExecuteVisitor.
     */
    String oddResultStepName = "oddResult";
    oddResultProvider.setName(oddResultStepName);
    String evenResultStepName = "evenResult";
    evenResultProvider.setName(evenResultStepName);

    /**
     * integerProvider is a step providing an integer. This integer is provided as an input of the flow.
     */
    DataProviderStep<Integer> integerProvider = new DataProviderStep<>(TypeToken.of(Integer.class));

    /**
     * ConditionalStep allow for conditional branching during the execution of flow.
     * conditional defined below checks the value provided by the integerProvider step.
     * If the value is an even number, the evenResultProvider step is executed.
     * If the value is an odd number, the oddResultProvider is executed.
     */
    ConditionalStep<String, Integer> conditional = new ConditionalStep<>(new Predicate<Integer>() {
        @Override
        public boolean apply(Integer input) {
            return input % 2 == 0;
        }
    }, integerProvider, evenResultProvider, oddResultProvider, TypeToken.of(String.class));

    String oddString = "I am an odd number";
    String evenString = "I am an even number";

    Integer[] inputs = { 1, 2 };
    for (Integer i : inputs) {
        /**
         * Create an ExecuteVisitor to execute the flow.
         */
        SimpleExecuteVisitor<String> executeVisitor = new SimpleExecuteVisitor<>();
        /**
         * Add the inputs to the visitor. Use the step name for the String DataProvider so the executor can differentiates
         * the two inputs and associate them with the right DataProvider.
         */
        executeVisitor.addInput(oddResultStepName, oddString);
        executeVisitor.addInput(evenResultStepName, evenString);
        executeVisitor.addInput(TypeToken.of(Integer.class), i);
        System.out.println(executeVisitor.execute(conditional));
        System.out.println();
    }
}

From source file:com.ondeck.datapipes.examples.SimpleFlowMergeStepExample.java

public static void main(String[] args) throws FlowException {
    DataProviderStep<String> dataProvider = new DataProviderStep<>(TypeToken.of(String.class));
    /**//w ww .j a v a2s  .  c o  m
     * Function step that counts the letters in the input string
     */
    FunctionStep<String, Integer> countLetters = new FunctionStep<>(new Function<String, Integer>() {
        @Override
        public Integer apply(String sourceValue) {
            Integer result = 0;
            for (Character c : sourceValue.toCharArray()) {
                if (Character.toString(c).matches("[a-zA-Z]")) {
                    result++;
                }
            }
            return result;
        }
    }, dataProvider, TypeToken.of(Integer.class));
    countLetters.setName("countLetters");

    /**
     * Function step that counts the numbers in the input string
     */
    FunctionStep<String, Integer> countNumbers = new FunctionStep<>(new Function<String, Integer>() {
        @Override
        public Integer apply(String sourceValue) {
            Integer result = 0;
            for (Character c : sourceValue.toCharArray()) {
                if (Character.toString(c).matches("[0-9]")) {
                    result++;
                }
            }
            return result;
        }
    }, dataProvider, TypeToken.of(Integer.class));
    countNumbers.setName("countNumbers");

    /**
     * Merge step that merges results of the two function steps
     */
    MergeStep<String> mergeStep = new MergeStep<>(new MergeStep.DataMerger<String>() {
        @Override
        public String merge(Map<Object, Object> data) throws MergeStep.MergeException {
            Integer letterResult = getData("countLetters", data);
            Integer numberResult = getData("countNumbers", data);
            return String.format("There are %d letters and  %d numbers", letterResult, numberResult);
        }
    }, TypeToken.of(String.class), countLetters, countNumbers);

    /**
     * Execute the flow
     */
    SimpleExecuteVisitor<String> executeVisitor = new SimpleExecuteVisitor<>();
    executeVisitor.addInput(new TypeToken<String>() {
    }, INPUT_STRING);
    System.out.print(executeVisitor.execute(mergeStep));
}

From source file:org.inspirenxe.alfred.Main.java

public static void main(String[] args) throws IOException, ObjectMappingException {
    // ./config.conf
    final Path configPath = Paths.get("config.conf");
    if (Files.notExists(configPath)) {
        InputStream stream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(configPath.toString());
        Files.copy(stream, configPath);
    }//w w w  . j  a v  a2s .  c  o  m
    loader = HoconConfigurationLoader.builder().setPath(configPath).build();
    node = loader.load();
    IRC_CLIENT = generateClient();
    IRC_CLIENT.getEventManager().registerEventListener(new Listener());
    for (String channel : node.getNode("irc", "channels").getList(TypeToken.of(String.class))) {
        IRC_CLIENT.addChannel(channel);
    }
}

From source file:com.ondeck.datapipes.examples.SimpleFlowMultiStepExample.java

public static void main(String[] args) throws FlowException {
    DataProviderStep<List<String>> dataProvider = new DataProviderStep<>(new TypeToken<List<String>>() {
    });//from  www  .j  a v a 2 s  .  c o m

    /**
     * A MultiStep allow to apply the same treatment to all element of a collection. The step named sub defined below
     * converts a String to an Integer. Notice how the parent step of sub is null.
     */
    FunctionStep<String, Integer> sub = new FunctionStep<>(new Function<String, Integer>() {
        @Override
        public Integer apply(String input) {
            System.out.println(Thread.currentThread().getName() + " executing multi step sub step");
            return Integer.valueOf(input);
        }
    }, null, TypeToken.of(Integer.class));

    /**
     *  multi applies the treatment defined by sub to each element provided by the output of the parent step dataProvider.
     */
    MultiStep<String, Integer, List<String>, ArrayList<Integer>> multi = new MultiStep<>(sub, dataProvider,
            new TypeToken<ArrayList<Integer>>() {
            });

    /**
     *  Finally use an ExecuteVisitor to execute the flow. Using a ParallelExecuteVisitor allows for parallel execution
     *  of each substep of the multi step.
     */
    ExecuteVisitor<ArrayList<Integer>> executeVisitor = new ParallelExecuteVisitor<>(
            Executors.newCachedThreadPool());
    executeVisitor.addInput(new TypeToken<List<String>>() {
    }, Arrays.asList("1", "2", "3"));
    List<Integer> result = executeVisitor.execute(multi);
    System.out.println(result);
}

From source file:com.ondeck.datapipes.examples.AuditFlowExample.java

public static void main(String[] args) throws FlowException, IOException {
    /**/*from  ww  w  . j a va  2 s .  co  m*/
     * The flow takes a list of String as input
     */
    DataProviderStep<List<String>> stringListProvider = new DataProviderStep<>(new TypeToken<List<String>>() {
    });

    /**
     * Each string element of the input is converted to an integer.
     */
    FunctionStep<String, Integer> toInteger = new FunctionStep<>(new Function<String, Integer>() {
        @Override
        public Integer apply(String input) {
            return Integer.valueOf(input);
        }
    }, null, TypeToken.of(Integer.class));
    MultiStep<String, Integer, List<String>, ArrayList<Integer>> integerList = new MultiStep<>(toInteger,
            stringListProvider, new TypeToken<ArrayList<Integer>>() {
            });

    /**
     * Each integer is then squared.
     */
    FunctionStep<Integer, Integer> square = new FunctionStep<>(new Function<Integer, Integer>() {
        @Override
        public Integer apply(Integer input) {
            return input * input;
        }
    }, null, TypeToken.of(Integer.class));

    MultiStep<Integer, Integer, ArrayList<Integer>, ArrayList<Integer>> squareList = new MultiStep<>(square,
            integerList, new TypeToken<ArrayList<Integer>>() {
            });

    /**
     * All squared integer are then summed up.
     */
    FunctionStep<List<Integer>, Integer> sum = new FunctionStep<>(new Function<List<Integer>, Integer>() {
        @Override
        public Integer apply(List<Integer> input) {
            int acc = 0;
            for (Integer i : input) {
                acc += i;
            }
            return acc;
        }
    }, squareList, TypeToken.of(Integer.class));

    /**
     * Create an AuditConfiguration which will tell which steps of the flow must be audited and how.
     */
    AuditConfiguration auditConfiguration = new AuditConfiguration();
    /**
     * Create an IntegerAuditor which provide the logic to audit an integer.
     */
    IntegerAuditor integerAuditor = new IntegerAuditor();
    /**
     * Register that we want to audit the integerList, squareList and sum steps. Note that a step returning a type T
     * shoud be audited by an Auditor<T> except for MultiStep; MultiStep returning a Collection<T> must be audited by
     * an Auditor<T>.
     */
    auditConfiguration.addAuditor(integerList, integerAuditor);
    auditConfiguration.addAuditor(squareList, integerAuditor);
    auditConfiguration.addAuditor(sum, integerAuditor);

    {
        /**
         * Execute the flow using an ExecuteVisitor.
         */
        ExecuteVisitor<Integer> executeVisitor = new SimpleExecuteVisitor<>();
        executeVisitor.addInput(new TypeToken<List<String>>() {
        }, Arrays.asList("1", "42", "2015"));
        Integer result = executeVisitor.execute(sum);
        System.out.println("Result: " + result);

        /**
         * Audit the flow using an AuditVisitor
         */
        AuditVisitor auditVisitor = new AuditVisitor(executeVisitor.getStepResults(), auditConfiguration);
        Collection<AuditReport> auditReports = auditVisitor.audit(sum);
        /**
         * The returned collection contains a tree like structure showing how audited step results are linked to each other.
         */
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(auditReports));
    }

    /**
     * Auditing can also record execution timing information.
     */
    {
        ExecuteVisitor<Integer> executeVisitor = new SimpleExecuteVisitor<>();
        /**
         * Recording execution time requires to add a TimingListener to the ExecuteVisitor.
         */
        TimingListener<Date> timingListener = new TimingListener<>(new Function<Void, Date>() {
            @Override
            public Date apply(Void input) {
                return new Date();
            }
        });
        executeVisitor.addListener(timingListener);
        executeVisitor.addInput(new TypeToken<List<String>>() {
        }, Arrays.asList("1", "42", "2015"));
        Integer result = executeVisitor.execute(sum);
        System.out.println("Result: " + result);

        /**
         * Audit the flow using a TimedAuditVisitor
         */
        TimedAuditVisitor<Date> timedAuditVisitor = new TimedAuditVisitor<>(executeVisitor.getStepResults(),
                auditConfiguration, timingListener.getTimings());
        Collection<TimedAuditReport<Date>> auditReports = timedAuditVisitor.audit(sum);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(auditReports));
    }
}

From source file:org.zalando.switchboard.TypeResolver.java

static <T> Class<T> resolve(final Object instance, final Class<?> type, final int index) {
    final TypeToken<?> token = TypeToken.of(instance.getClass());
    final TypeToken<?> resolved = token.resolveType(type.getTypeParameters()[index]);
    return cast(resolved.getRawType());
}

From source file:com.google.cloud.trace.jdbc.Proxies.java

/** Returns all interfaces implemented by the given object. */
private static Class<?>[] getInterfaces(Object o) {
    checkNotNull(o);/*from   w  w w  .j av  a2  s.  c  o m*/

    return TypeToken.of(o.getClass()).getTypes().interfaces().rawTypes().toArray(new Class<?>[0]);
}

From source file:de.dfki.kiara.ktd.ObjectType.java

public static ObjectType get(World world, Class<?> clazz) {
    return get(world, TypeToken.of(clazz));
}