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

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

Introduction

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

Prototype

protected TypeToken() 

Source Link

Document

Constructs a new type token of T .

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>>() {

    };//ww w .j  a  v  a 2s . com
    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.SimpleFlowMultiStepExample.java

public static void main(String[] args) throws FlowException {
    DataProviderStep<List<String>> dataProvider = new DataProviderStep<>(new TypeToken<List<String>>() {
    });// w w w  .  ja v  a2 s  .c  om

    /**
     * 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 {
    /**/*w  ww .j  a v a  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:com.ondeck.datapipes.examples.SimpleFlowExample.java

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

    /**//  ww  w .  java 2  s. c  o m
     * 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.SimpleFlowMergeStepExample.java

public static void main(String[] args) throws FlowException {
    DataProviderStep<String> dataProvider = new DataProviderStep<>(TypeToken.of(String.class));
    /**/*from w  w w .jav 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:com.inkubator.common.util.NewMain.java

/**
 * @param args the command line arguments
 *//*from  w w w. j  ava2  s.c om*/
public static void main(String[] args) throws IOException {

    File file1 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page1.txt");
    File file2 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page2.txt");
    //        File file3 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\json\\json\\menado\\page3.txt");
    File file3 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page3.txt");
    File file4 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page4.txt");
    File file5 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page5.txt");
    File file6 = new File(
            "C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\JSON_Ek\\Surabaya\\Page6.txt");
    //        File file7 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 7.txt");
    //        File file8 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 8.txt");
    //        File file9 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 9.txt");
    //        File file10 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 10.txt");
    //        File file11 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 11.txt");
    //        File file12 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 12.txt");
    //        File file13 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 13.txt");
    //        File file14 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 14.txt");
    //        File file15 = new File("C:\\Users\\deni.fahri\\AppData\\Roaming\\Skype\\My Skype Received Files\\Bandung\\Bandung\\Page 15.txt");
    //        File file16 = new File("C:\\Users\\deni.fahri\\Downloads\\page16.txt");

    //        File file2 = new File("C:\\Users\\deni.fahri\\Documents\\hasil.txt");
    String agoda = FilesUtil.getAsStringFromFile(file1);
    String agoda1 = FilesUtil.getAsStringFromFile(file2);
    String agoda2 = FilesUtil.getAsStringFromFile(file3);
    String agoda3 = FilesUtil.getAsStringFromFile(file4);
    String agoda4 = FilesUtil.getAsStringFromFile(file5);
    String agoda5 = FilesUtil.getAsStringFromFile(file6);
    //        String agoda6 = FilesUtil.getAsStringFromFile(file7);
    //        String agoda7 = FilesUtil.getAsStringFromFile(file8);
    //        String agoda8 = FilesUtil.getAsStringFromFile(file9);
    //        String agoda9 = FilesUtil.getAsStringFromFile(file10);
    //        String agoda10 = FilesUtil.getAsStringFromFile(file11);
    //        String agoda11 = FilesUtil.getAsStringFromFile(file12);
    //        String agoda12 = FilesUtil.getAsStringFromFile(file13);
    //        String agoda13 = FilesUtil.getAsStringFromFile(file14);
    //        String agoda14 = FilesUtil.getAsStringFromFile(file15);
    //        String agoda15 = FilesUtil.getAsStringFromFile(file16);
    ////        System.out.println(" Test Nya adalah :" + agoda);
    ////        String a=StringUtils.substringAfter("\"HotelTranslatedName\":", agoda);
    ////        System.out.println(" hasil; "+a);
    ////        // TODO code application logic here
    ////        System.out.println("Nilai " + JsonConverter.getValueByKeyStatic(agoda, "HotelTranslatedName"));
    TypeToken<List<HotelModel>> token = new TypeToken<List<HotelModel>>() {
    };
    Gson gson = new GsonBuilder().create();
    //        List<HotelModel> data = new ArrayList<>();
    //        HotelModel hotelModel = new HotelModel();
    //        hotelModel.setAddress("sdfsdffsfsdfsdfdsfdsf");
    //        hotelModel.setAccommodationName("Aku");
    //        HotelModel hotelModel1 = new HotelModel();
    //        hotelModel1.setAddress("sdfsdffsfsdfsdfdsfdsf");
    //        hotelModel1.setAccommodationName("Avvvku");
    //        HotelModel hotelModel2 = new HotelModel();
    //        hotelModel2.setAddress("sdfsdffsfsdfsdfdsfdsf");
    //        hotelModel2.setAccommodationName("Akvvvu");
    //        data.add(hotelModel);
    //        data.add(hotelModel1);
    //        data.add(hotelModel2);
    //        String json = gson.toJson(data);
    List<HotelModel> total = new ArrayList<>();
    List<HotelModel> data1 = new ArrayList<>();
    List<HotelModel> data2 = new ArrayList<>();
    List<HotelModel> data3 = new ArrayList<>();
    List<HotelModel> data4 = new ArrayList<>();
    List<HotelModel> data5 = new ArrayList<>();
    List<HotelModel> data6 = new ArrayList<>();
    List<HotelModel> data7 = new ArrayList<>();
    List<HotelModel> data8 = new ArrayList<>();
    List<HotelModel> data9 = new ArrayList<>();
    List<HotelModel> data10 = new ArrayList<>();
    List<HotelModel> data11 = new ArrayList<>();
    List<HotelModel> data12 = new ArrayList<>();
    List<HotelModel> data13 = new ArrayList<>();
    List<HotelModel> data14 = new ArrayList<>();
    List<HotelModel> data15 = new ArrayList<>();
    List<HotelModel> data16 = new ArrayList<>();

    data1 = gson.fromJson(agoda, token.getType());
    data2 = gson.fromJson(agoda1, token.getType());
    data3 = gson.fromJson(agoda2, token.getType());
    data4 = gson.fromJson(agoda3, token.getType());
    data5 = gson.fromJson(agoda4, token.getType());
    data6 = gson.fromJson(agoda5, token.getType());
    //        data7 = gson.fromJson(agoda6, token.getType());
    //        data8 = gson.fromJson(agoda7, token.getType());
    //        data9 = gson.fromJson(agoda8, token.getType());
    //        data10 = gson.fromJson(agoda9, token.getType());
    //        data11 = gson.fromJson(agoda10, token.getType());
    //        data12 = gson.fromJson(agoda11, token.getType());
    //        data13 = gson.fromJson(agoda12, token.getType());
    //        data14 = gson.fromJson(agoda13, token.getType());
    //        data15 = gson.fromJson(agoda14, token.getType());
    //        data16 = gson.fromJson(agoda15, token.getType());
    total.addAll(data1);
    total.addAll(data2);
    total.addAll(data3);
    total.addAll(data4);
    total.addAll(data5);
    total.addAll(data6);
    //        total.addAll(data7);
    //        total.addAll(data8);
    //        total.addAll(data9);
    //        total.addAll(data10);
    //        total.addAll(data11);
    //        total.addAll(data12);
    //        total.addAll(data13);
    //        total.addAll(data14);
    //        total.addAll(data15);
    //        total.addAll(data16);
    System.out.println(" Ukurannn nya " + total.size());

    //        System.out.println(" Ukurannya " + data2.size());
    for (HotelModel mode : total) {
        System.out.println(mode);
    }
    //        HotelModel hotelModel = gson.fromJson(agoda, HotelModel.class);
    //        String Data = hotelModel.getHotelTranslatedName() + ";" + hotelModel.getStarRating() + ";" + hotelModel.getAddress() + ";" + hotelModel.getIsFreeWifi();
    //        FilesUtil.writeToFileFromString(file2, Data);
    //        System.out.println(hotelModel);
    //
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("Agoda Data Hotel Surabaya");

    ////
    TreeMap<String, Object[]> datatoExel = new TreeMap<>();
    int i = 1;
    //        datatoExel.put("1", new Object[]{"Hotel Agoda Jakarta"});
    datatoExel.put("1", new Object[] { "Nama Hotel", "Arena", "Alamat", "Rating", "Apakah Gratis Wifi",
            "Harga Mulai Dari", "Longitude", "Latitude" });
    for (HotelModel mode : total) {
        datatoExel.put(String.valueOf(i + 1),
                new Object[] { mode.getHotelTranslatedName(), mode.getAreaName(), mode.getAddress(),
                        mode.getStarRating(), mode.getIsFreeWifi(),
                        mode.getTextPrice() + " " + mode.getCurrencyCode(), mode.getCoordinate().getLongitude(),
                        mode.getCoordinate().getLatitude() });
        i++;
    }
    //
    ////          int i=1;
    ////        for (HotelModel mode : data2) {
    ////             datatoExel.put(String.valueOf(i), new Object[]{1d, "John", 1500000d});
    //////        }
    ////       
    ////        datatoExel.put("4", new Object[]{3d, "Dean", 700000d});
    ////
    Set<String> keyset = datatoExel.keySet();
    int rownum = 0;
    for (String key : keyset) {
        Row row = sheet.createRow(rownum++);
        Object[] objArr = datatoExel.get(key);
        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            if (obj instanceof Date) {
                cell.setCellValue((Date) obj);
            } else if (obj instanceof Boolean) {
                cell.setCellValue((Boolean) obj);
            } else if (obj instanceof String) {
                cell.setCellValue((String) obj);
            } else if (obj instanceof Double) {
                cell.setCellValue((Double) obj);
            }
        }
    }

    try {
        FileOutputStream out = new FileOutputStream(new File("C:\\Users\\deni.fahri\\Documents\\Surabaya.xls"));
        workbook.write(out);
        out.close();
        System.out.println("Excel written successfully..");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:utils.JSONConverter.java

public static List<Person> getPersonListFromJson(String js) {
    List<Person> list = gson.fromJson(js, new TypeToken<List<Person>>() {
    }.getType());//  w ww.  j a  v a2s .  c  o  m
    return list;
}

From source file:com.seventh_root.ld33.server.config.Config.java

public static Config load(File file) throws IOException {
    Reader reader = new FileReader(file);
    Gson gson = new Gson();
    Map<String, Object> deserialised = gson.fromJson(reader, new TypeToken<HashMap<String, Object>>() {
    }.getType());/*w w w  .jav a  2  s.  c o m*/
    reader.close();
    Map<String, Object> config = new HashMap<>();
    config.putAll(deserialised);
    return new Config(config);
}

From source file:com.cognifide.aet.communication.api.metadata.SuiteReaderHelper.java

static Suite readSuiteFromFile(String resource, ClassLoader classLoader) throws IOException {
    String json = IOUtils.toString(classLoader.getResourceAsStream(resource));
    return GSON.fromJson(json, new TypeToken<Suite>() {
    }.getType());// ww  w  .  ja va  2s .c o  m
}

From source file:org.gradle.nativeplatform.internal.pch.DefaultPreCompiledHeaderTransformContainer.java

private static Class<LanguageTransform<?, ?>> getLanguageTransformType() {
    @SuppressWarnings("unchecked")
    Class<LanguageTransform<?, ?>> rawType = (Class<LanguageTransform<?, ?>>) new TypeToken<LanguageTransform<?, ?>>() {
    }.getRawType();/*from  www. j a v a2 s  .c  o  m*/
    return rawType;
}