Example usage for org.apache.commons.lang.time StopWatch toString

List of usage examples for org.apache.commons.lang.time StopWatch toString

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch toString.

Prototype

public String toString() 

Source Link

Document

Gets a summary of the time that the stopwatch recorded as a string.

The format used is ISO8601-like, hours:minutes:seconds.milliseconds.

Usage

From source file:org.op4j.BenchmarkTest.java

@Test
public void test() {

    try {//from w ww.  j a v a 2 s .c om

        final List<String> strings = new ArrayList<String>();
        for (int i = 0; i < STRUCTURE_SIZE; i++) {
            strings.add(RandomStringUtils.random(20));
        }

        final StopWatch stopWatch1 = new StopWatch();
        final StopWatch stopWatch2 = new StopWatch();

        int seed = RandomUtils.nextInt(2);
        boolean op4jFirst = Op.on(seed).exec(FnNumber.toBoolean()).get().booleanValue();

        if (op4jFirst) {

            stopWatch1.start();

            String[] upper1 = null;
            for (int i = 0; i < ITERATIONS; i++) {
                upper1 = Op.onList(strings).forEach().exec(FnString.toUpperCase()).endFor()
                        .toArrayOf(Types.STRING).get();
            }

            stopWatch1.stop();

            stopWatch2.start();

            String[] upper2 = null;
            for (int i = 0; i < ITERATIONS; i++) {
                List<String> upper2List = new ArrayList<String>();
                for (final String string : strings) {
                    upper2List.add(string.toUpperCase());
                }
                upper2 = upper2List.toArray(new String[upper2List.size()]);
            }

            stopWatch2.stop();

            System.out.println("With op4j:    " + stopWatch1.toString());

            System.out.println("Without op4j: " + stopWatch2.toString());

        } else {

            stopWatch1.start();

            String[] upper1 = null;
            for (int i = 0; i < ITERATIONS; i++) {
                List<String> upper1List = new ArrayList<String>();
                for (final String string : strings) {
                    upper1List.add(string.toUpperCase());
                }
                upper1 = upper1List.toArray(new String[upper1List.size()]);
            }

            stopWatch1.stop();

            stopWatch2.start();

            String[] upper2 = null;
            for (int i = 0; i < ITERATIONS; i++) {
                upper2 = Op.onList(strings).forEach().exec(FnString.toUpperCase()).endFor()
                        .toArrayOf(Types.STRING).get();
            }

            stopWatch2.stop();

            System.out.println("Without op4j: " + stopWatch1.toString());

            System.out.println("With op4j:    " + stopWatch2.toString());

        }

        StopWatch op4jWatch = new StopWatch();

        Level0ListOperator<List<String>, String> op1 = null;
        op4jWatch.start();
        for (int i = 0; i < ITERATIONS; i++) {
            op1 = Op.onList(strings);
        }
        op4jWatch.stop();

        String time1 = op4jWatch.toString();
        op4jWatch.reset();

        Level1ListElementsOperator<List<String>, String> op2 = null;
        op4jWatch.start();
        for (int i = 0; i < ITERATIONS; i++) {
            op2 = op1.forEach();
        }
        op4jWatch.stop();

        String time2 = op4jWatch.toString();
        op4jWatch.reset();

        Level1ListElementsOperator<List<String>, String> op3 = null;
        op4jWatch.start();
        for (int i = 0; i < ITERATIONS; i++) {
            op3 = op2.exec(FnString.toUpperCase());
        }
        op4jWatch.stop();

        String time3 = op4jWatch.toString();
        op4jWatch.reset();

        Level0ListOperator<List<String>, String> op4 = null;
        op4jWatch.start();
        for (int i = 0; i < ITERATIONS; i++) {
            op4 = op3.endFor();
        }
        op4jWatch.stop();

        String time4 = op4jWatch.toString();
        op4jWatch.reset();

        Level0ArrayOperator<List<String>, String> op5 = null;
        op4jWatch.start();
        for (int i = 0; i < ITERATIONS; i++) {
            op5 = op4.toArrayOf(Types.STRING);
        }
        op4jWatch.stop();

        String time5 = op4jWatch.toString();
        op4jWatch.reset();

        String[] op6 = null;
        op4jWatch.start();
        for (int i = 0; i < ITERATIONS; i++) {
            op6 = op5.get();
        }
        op4jWatch.stop();

        String time6 = op4jWatch.toString();
        op4jWatch.reset();

        System.out.println("Time 01: " + time1);
        System.out.println("Time 02: " + time2);
        System.out.println("Time 03: " + time3);
        System.out.println("Time 04: " + time4);
        System.out.println("Time 05: " + time5);
        System.out.println("Time 06: " + time6);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.op4j.MiscTest.java

@Test
public void test() throws Exception {

    final StopWatch watch = new StopWatch();
    watch.start();//from   w  w  w.  ja va2s . c  o  m

    final String[] stringsArr1 = new String[] { "Hello", "Goodbye", null };
    final List<String> stringsList1 = Arrays.asList(stringsArr1);

    final String[][] stringsStrings1 = new String[][] { new String[] { "Hello!", "Goodbye!" },
            new String[] { "Hola!", "Adis!" } };
    final List<String>[] stringsListStrings1 = (List<String>[]) new List<?>[] {
            Arrays.asList(new String[] { "Hello!", "Goodbye!" }),
            Arrays.asList(new String[] { "Hola!", "Adis!" }) };
    final List<List<String>> stringsListStringsList1 = Arrays.asList(stringsListStrings1);

    final Map<String, String> map1 = new LinkedHashMap<String, String>();
    map1.put("es", "Hola!");
    map1.put("en", "Hello!");
    map1.put("gl", "Ola!");
    map1.put("ca", "Hola!");

    final Map<String, String> map2 = new LinkedHashMap<String, String>();
    map2.put("es", "Adis!");
    map2.put("en", "Goodbye!");
    map2.put("gl", "Adus!");
    map2.put("ca", "Adu!");
    map2.put("fr", "Adieu!");

    final Map<String, String>[] maps1 = (Map<String, String>[]) new Map<?, ?>[] { map1, map2 };

    System.out.println(Op.onList(stringsList1).get());
    System.out.println(Op.onList(stringsList1).forEach().get());

    final BigDecimal bd = new BigDecimal("3455234.6325");
    final Float f = Float.valueOf(3455234.6325f);
    final Double d = Double.valueOf(3455234.6325);

    System.out.println(bd.doubleValue());
    System.out.println(f);
    System.out.println(d);

    System.out.println(
            Op.onList(Arrays.asList(new Integer[] { 2, 3, 4, 1, 2, 2, 4, 5, 2, 3, 5, 6, 87, 45, 2, 3, 34, 1 }))
                    .get());
    System.out.println(
            Op.onList(Arrays.asList(new Integer[] { 2, 3, 4, 1, 2, 2, 4, 5, 2, 3, 5, 6, 87, 45, 2, 3, 34, 1 }))
                    .distinct().get());

    final List<List<String>> listOfListOfString1 = Arrays.asList((List<String>[]) new List<?>[] {
            Arrays.asList(new String[] { "a", "b", "a" }), Arrays.asList(new String[] { "a", "b", "a" }) });

    final Set<Set<String>> setOfsetOfString1 = new LinkedHashSet<Set<String>>(
            Arrays.asList((Set<String>[]) new Set<?>[] {
                    new LinkedHashSet<String>(Arrays.asList(new String[] { "a", "b", "a" })),
                    new LinkedHashSet<String>(Arrays.asList(new String[] { "a", "b", "a" })) }));

    final String[][] arrayOfArrayOfString1 = new String[][] { new String[] { "a", "b", "a" },
            new String[] { "a", "b", "a" } };

    System.out.println(Op.onList(stringsList1).addAll("World!", "Mars!").get());
    System.out.println(Op.onList(stringsList1).insertAll(1, "World!", "Mars!").get());
    System.out.println(Op.onList(stringsList1).addAll(stringsList1).get());
    System.out.println(Op.onList(stringsList1).get());
    System.out.println(Op.onList(stringsList1).removeAllIndexes(0, 2).get());
    System.out.println(Op.onList(stringsList1).removeAllIndexesNot(0).get());
    System.out.println(Op.onList(stringsList1).removeAllIndexesNot(0, 2).get());
    System.out.println(Op.onList(stringsList1).removeAllTrue(new IFunction<String, Boolean>() {

        public Boolean execute(String target, final ExecCtx ctx) {
            return Boolean.valueOf(target == null);
        }

    }).get());
    System.out.println(Op.onList(stringsList1).removeAllNull().get());

    System.out.println("================");

    final Set<String> stringSet1 = new LinkedHashSet<String>(stringsList1);
    System.out.println(Op.onSet(stringSet1).addAll("World!", "Mars!").get());
    System.out.println(Op.onSet(stringSet1).insertAll(1, "World!", "Mars!").get());
    System.out.println(Op.onSet(stringSet1).addAll(stringsList1).get());
    System.out.println("---");
    System.out.println(Op.onSet(stringSet1).get());
    System.out.println(Op.onSet(stringSet1).removeAllIndexes(0, 2).get());
    System.out.println(Op.onSet(stringSet1).removeAllIndexesNot(0).get());
    System.out.println(Op.onSet(stringSet1).removeAllIndexesNot(0, 2).get());
    System.out.println(Op.onSet(stringSet1).removeAllNull().get());

    System.out.println(
            printArray(Op.onArrayOf(Types.STRING, stringsArr1).insertAll(2, "lalero", "lururu").get()));

    System.out.println(Op.onMap(map1).put("fr", "All!").get());
    System.out.println(Op.onMap(map1).insert(0, "fr", "All!").get());
    System.out.println(Op.onMap(map1).insert(2, "fr", "All!").get());
    System.out.println(Op.onMap(map2).get());
    System.out.println(Op.onMap(map2).putAll(Op.onMap(map1).insert(0, "gl", "Meuuuu!").get()).get());

    System.out.println(Op.onListFor(234, 12, 231));
    System.out.println(Op.onListFor(234).addAll(10));
    System.out.println(Op.onListFor(234).insert(0, 10));
    System.out.println(Op.onListFor(234).addAll(10).insert(1, 3));
    System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).addAll((Integer) null));
    System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).addAll((Integer) null).removeAllNull());
    System.out.println(Op.onListFor(234).addAll(10).insert(1, 3).removeAllIndexesNot(1));
    System.out.println(printArray(Op.on(234).intoSingletonArrayOf(Types.INTEGER).addAll(8).get()));
    System.out.println(Op.on((List) null).addAll(123));
    System.out.println(Op.on((Object) null).intoSingletonList().get());
    System.out.println(Op.on((Object) null).intoSingletonSet().get());
    System.out.println(printArray(Op.on((String) null).intoSingletonArrayOf(Types.STRING).addAll("a")
            .removeAllNull().removeAllIndexes(0).get()));

    //        System.out.println(printArray(Op.buildArrayOfArray(Types.STRING).addAll(Op.buildArray(Types.STRING).addAll("a","b").get()).addAll(Op.buildArray(Types.STRING).addAll("1","2","3").get()).get()));
    //        System.out.println(Op.buildMap(Types.INTEGER,Types.STRING).put(12,"hello!").get());
    System.out.println(Op.onListFor("a", 1, "b", 3).couple().get());

    System.out.println(Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").sort().get());
    System.out.println(
            Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").toSet().sort(new Comparator<String>() {

                public int compare(String o1, String o2) {
                    if (o1.length() < o2.length()) {
                        return -1;
                    } else if (o1.length() == o2.length()) {
                        return 0;
                    }
                    return 1;
                }

            }).get());

    System.out.println(printArray(
            Op.onListFor("hello", "goodbye", "adios", "ciao", "hola").toArrayOf(Types.STRING).sort().get()));
    System.out.println(printArray(Op.onListFor("hello", "goodbye", "adios", "ciao", "hola")
            .toArrayOf(Types.STRING).sort(new Comparator<String>() {

                public int compare(String o1, String o2) {
                    if (o1.length() < o2.length()) {
                        return -1;
                    } else if (o1.length() == o2.length()) {
                        return 0;
                    }
                    return 1;
                }

            }).get()));

    System.out.println(
            Op.on("12314123.4123").exec(FnString.toInteger(RoundingMode.CEILING, DecimalPoint.IS_POINT)).get());
    System.out.println(
            Op.on("12314123.4123").exec(FnString.toInteger(RoundingMode.CEILING, DecimalPoint.IS_POINT)).get());
    System.out.println(Op.on("12314123").exec(FnString.toInteger()).get());
    System.out.println(Op.on("12314123").exec(FnString.toLong()).get());
    System.out.println(Op.on("12314123").exec(FnString.toBigInteger()).get());
    System.out.println(Op.on("12314123.4123").exec(FnString.toDouble()).get());
    System.out.println(Op.on("12314123.4123").exec(FnString.toDouble(3, RoundingMode.CEILING)).get());
    System.out.println(Op.on("12314123.4123").exec(FnString.toBigDecimal(3, RoundingMode.CEILING)).get());

    final SimpleDateFormat dateFormat = new SimpleDateFormat();
    System.out.println(dateFormat
            .format(Op.on(Calendar.getInstance()).exec(FnCalendar.truncate(Calendar.DATE)).get().getTime()));

    System.out.println(dateFormat
            .format(Op.on("25/nov/1979").exec(FnString.toCalendar("dd/MMM/yyyy", "es")).get().getTime()));

    //        System.out.println(dateFormat.format(Op.onAll(1979, 11, 25, 12, 30).buildList().exec(ToCalendar.fromString("dd/MMM/yyyy", "es")).get().getTime()));
    System.out.println(dateFormat.format(Op.on(Op.onListFor(1979, 11, 25, 12, 30).get())
            .exec(FnCalendar.fieldIntegerListToCalendar()).get().getTime()));
    System.out.println(dateFormat.format(Op.on(Op.onListFor("1979", "11", "25", "12", "30").get())
            .toArrayOf(Types.STRING).exec(FnCalendar.fieldStringArrayToCalendar()).get().getTime()));

    System.out.println(Op.on(Op.onListFor(1979, 11, 25, 12, 30).get()).exec(FnList.ofInteger().sort()).get());
    System.out.println(Op.on(Op.onSetFor(1979, 11, 25, 12, 30).get()).exec(FnSet.ofInteger().sort()).get());
    System.out.println(Op.on(Op.onListFor(1979, 11, 25, 12, 30, 1980, 2, 43, 12, 11).get())
            .exec(FnList.ofInteger().distinct()).get());

    System.out.println(Op.on("hello").intoSingletonList().get());
    System.out.println(printArray(Op.on("hello").intoSingletonArrayOf(Types.STRING).get()));

    //        System.out.println(Op.buildList(Types.CALENDAR)
    //              .addAll(Calendar.getInstance(), Calendar.getInstance())
    //              .forEach().exec(ToString.fromCalendar(DateStyle.FULL, TimeStyle.NONE, Locale.UK)).get());
    //        
    //        System.out.println(Op.buildList(Types.CALENDAR)
    //              .addAll(Calendar.getInstance(), Calendar.getInstance())
    //              .forEach().exec(ToString.fromCalendar(DateStyle.FULL, TimeStyle.SHORT, Locale.UK)).get());
    //        
    //        System.out.println(Op.buildList(Types.CALENDAR)
    //              .addAll(Calendar.getInstance(), Calendar.getInstance())
    //              .forEach().exec(ToString.fromCalendar("dd-MMM-yyyy", Locale.UK)).get());
    //            
    //        System.out.println(Op.buildList(Types.CALENDAR)
    //              .addAll(Calendar.getInstance(), Calendar.getInstance())
    //              .forEach().exec(ToString.fromCalendar("dd-MMMM-yyyy")).get());
    //        
    //        System.out.println(Op.buildList(Types.DATE)
    //              .addAll(new java.sql.Date(Calendar.getInstance().getTimeInMillis()))
    //              .forEach().exec(ToString.fromDate("dd-MMM-yyyy", Locale.UK)).get());
    //        
    //        
    //        System.out.println(Op.buildList(Types.STRING)
    //              .addAll("  Company ", " day ")
    //              .forEach().exec(StringFuncs.trim()).get());
    //        System.out.println(Op.buildList(Types.STRING)
    //              .addAll("  Company ", " day ")
    //              .forEach().exec(StringFuncs.trim()).exec(StringFuncs.toUpperCase()).get());

    System.out.println(Op.on("Dublin").exec(FnString.toHexadecimal(Charset.forName("ISO-8859-1")))
            .exec(FnString.fromHexadecimal(Charset.forName("ISO-8859-1"))).get());

    //        System.out.println(Op.buildList(Types.NUMBER)
    //                .addAll(45.9, new BigDecimal(34.456))
    //                .forEach().exec(ToString.fromCurrency(Locale.getDefault(), 
    //                        1, 2, 10, true)).get());
    //        System.out.println(Op.buildList(Types.NUMBER)
    //                .addAll(45.9, 45, new BigDecimal(34.456))
    //                .forEach().exec(ToString.fromCurrency(Locale.getDefault(), 
    //                        1, 0, 0, true)).get());
    //        
    //        System.out.println(Op.buildList(Types.NUMBER)
    //                .addAll(45.9, 45, new BigDecimal(34.456), 0, 0.5, 0.211)
    //                .forEach().exec(ToString.fromPercent(Locale.getDefault(), 
    //                        1, 0, 10, ',', '\'', false)).get());

    System.out.println(Op.onArrayOf(Types.STRING, stringsArr1).toSet().get());

    final List<String[]> listOfStringArray1 = new ArrayList<String[]>();
    listOfStringArray1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toArrayOf(Types.STRING).get());
    listOfStringArray1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toArrayOf(Types.STRING).get());

    final List<Set<String>> listOfStringSet1 = new ArrayList<Set<String>>();
    listOfStringSet1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toSet().get());
    listOfStringSet1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toSet().get());

    final Set<String[]> setOfStringArray1 = new LinkedHashSet<String[]>();
    setOfStringArray1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toArrayOf(Types.STRING).get());
    setOfStringArray1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toArrayOf(Types.STRING).get());

    final Set<List<String>> setOfStringList1 = new LinkedHashSet<List<String>>();
    setOfStringList1.add(Op.onArrayFor("Hola", "Hello", "Ciao", "Ola").toList().get());
    setOfStringList1.add(Op.onArrayFor("Adios", "Goodbye", "Ciao", "Adus").toList().get());

    final Set<Set<String>> setOfStringSet1 = new LinkedHashSet<Set<String>>();
    setOfStringSet1.add(Op.onListFor("Hola", "Hello", "Ciao", "Ola").toSet().get());
    setOfStringSet1.add(Op.onListFor("Adios", "Goodbye", "Ciao", "Adus").toSet().get());

    System.out.println(Op.on("http://www.google.es/search?q=op4j&unusedParam=unusedValue '' 2^2 ")
            .exec(FnString.escapeJavaScript()).get());
    System.out.println(
            Op.on("Body tag is written like \"<body>content here</body>\"").exec(FnString.escapeHTML()).get());

    System.out.println("***___****___****");
    System.out.println(Op.onList(stringsList1).forEach().ifNotNull().exec(FnString.toUpperCase()).get());
    System.out.println("***___****___****");

    System.out.println(Op.onList(listOfListOfString1).get());

    //        System.out.println(Op.onMap(map1).forEachEntry().exec(Ognl.forString("'in ' + #target.key + ' you say ' + #target.value")).get());

    System.out.println(Op.onList(stringsList1).removeAllNull().sort().get());

    //        final List<Map<String,String>> listOfMapOfStringString1 = 
    //          Op.buildList(Types.MAP_OF_STRING_STRING).add(map1).add(map2).get();
    //        
    //        System.out.println(printArray(Op.onListOfMap(listOfMapOfStringString1).toArrayOfMap().get()));

    System.out.println(Types.LIST_ITERATOR_OF_BOOLEAN.getSimpleName());

    System.out.println(Op.onList(stringsList1).get());
    System.out.println(Op.onList(stringsList1).forEach().replaceWith("op4j is great!").get());
    System.out.println(Op.onList(stringsList1).forEach().replaceIfNullWith("op4j is great!").get());
    System.out.println(printArray(
            Op.onArrayOf(Types.STRING, stringsArr1).forEach().replaceIfNullWith("op4j is great!").get()));
    System.out.println(printArray(Op.onArrayOf(Types.STRING, stringsArr1)
            .replaceWith(new String[] { "alpha", "beta" }).forEach().exec(FnString.toUpperCase()).get()));

    //        System.out.println(Op.buildListOfList(Types.STRING).add(stringsList1).add(stringsList1).get());
    //        System.out.println(Op.buildListOfList(Types.STRING).addAll(stringsList1, stringsList1).get());

    Op.on(Integer.valueOf(12)).exec(FnObject.intoSingletonArrayOf(Types.INTEGER)).get();

    watch.stop();

    System.out.println("TIME: " + watch.toString());

    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");
    System.out.println("**********************");

    List<String> list = Arrays.asList(new String[] { "12/10/1492", "6/12/1978", "15/07/2045", null });

    Set<String> set1 = new LinkedHashSet<String>(list);
    Set<String> set2 = Op.on(list).toSet().get();

    System.out.println("set1 : " + set1);
    System.out.println("set2 : " + set2);

    Set<Calendar> set3 = Op.on(list).toSet().forEach().exec(FnString.toCalendar("dd/MM/yyyy")).get();

    System.out.println("set3asStr : " + Op.on(set3).map(FnCalendar.toStr("EEEE dd MMMM yyyy")).get());

    Set<Calendar> set4 = Op.on(list).toSet().removeAllNull().forEach().exec(FnString.toCalendar("dd/MM/yyyy"))
            .get();

    System.out.println(
            "set4asStr : " + Op.on(set4).map(FnCalendar.toStr("EEEE dd MMMM yyyy", new Locale("en"))).get());

    Set<Calendar> set5 = Op.on(list).toSet().removeAllNull().map(FnString.toCalendar("dd/MM/yyyy")).get();

    System.out.println(
            "set5asStr : " + Op.on(set5).map(FnCalendar.toStr("EEEE dd MMMM yyyy", new Locale("en"))).get());

    Calendar now = Calendar.getInstance();
    Set<Calendar> set6 = Op.on(list).toSet().map(FnString.toCalendar("dd/MM/yyyy"))
            .removeAllNullOrTrue(FnCalendar.after(now)).get();

    System.out.println("set6asStr : "
            + Op.on(set6).map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get());

    // ****************************
    // WARNING: Non-op4j code!!
    // ****************************
    SimpleDateFormat dateFormat1 = new SimpleDateFormat("dd/MM/yyyy");
    Set<Calendar> set = new LinkedHashSet<Calendar>();
    for (String element : list) {
        if (element != null) {
            Date date = null;
            try {
                date = dateFormat1.parse(element);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(date.getTime());
            if (!calendar.after(now)) {
                set.add(calendar);
            }
        }
    }

    System.out.println("setasStr : "
            + Op.on(set).map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get());

    Function<List<String>, Set<Calendar>> conversionFunction = Fn.onListOf(Types.STRING).toSet()
            .map(FnString.toCalendar("dd/MM/yyyy")).removeAllNullOrTrue(FnCalendar.after(now)).get();

    System.out.println("setFnasStr : " + Op.on(conversionFunction.execute(list))
            .map(FnCalendar.toStr("EEEE dd MMMM yyyy HH:mm:ss", new Locale("en"))).get());

    int[] v1 = new int[] { 3, 2, 1, 3 };
    long[] v2 = new long[] { 3, 2, 1, 3 };

    Op.on(1).get();
    List<Integer> iL = Op.onListFor(2, 1, 4, 213).get();
    System.out.println(iL);

    System.out.println(Arrays.asList(Op.on(v1).forEach().exec(FnInteger.add(Integer.valueOf(10))).get()));

    Op.on(v2).forEach().get();

    Op.on(123).exec(new IFunction<Integer, String>() {
        public String execute(Integer input, ExecCtx ctx) throws Exception {
            return "The input number is: " + input;
        }
    }).get();

    System.out.println(Op.on(23.24).exec(FnDouble.add(43)).get());

    System.out.println(Op.on(BigDecimal.valueOf(23.24)).exec(FnBigDecimal.add(1.2)).get());

    System.out.println(Op.onListFor(30, 30, 40).map(FnNumber.toBigInteger())
            .exec(FnBigInteger.avg(RoundingMode.CEILING)).get());

    System.out.println(Op.on(10).exec(FnInteger.divideBy(3, RoundingMode.CEILING)).get());

    Function<Integer, Boolean> fnAnd1 = FnBoolean.and(FnObject.eq("lala"), FnNumber.notEq(534));

    System.out.println(Op.on(233).exec(FnBoolean.and(FnNumber.greaterThan(44), FnObject.lessThan(534))).get());

    System.out.println(
            Op.on(1233).ifTrue(FnBoolean.not(FnBoolean.and(FnNumber.greaterThan(44), FnObject.lessThan(534))))
                    .exec(FnInteger.add(10)).get());

    System.out.println(Op.on(1233).exec(FnFunc.chain(FnInteger.add(10), FnNumber.greaterThan(1200))).get());

    System.out.println(Op.onListFor(1, 2, 3, 4).exec(FnList.ofInteger().containsAny(12, 3)).get());

    String[] arr231 = new String[] { "be", "a", "31aa", "31_l", "31A" };

    System.out.println(Arrays.asList(FnArray.ofString().sort().execute(arr231)));
    System.out
            .println(Arrays.asList(FnArray.ofString().sortBy(Call.methodForInteger("length")).execute(arr231)));

    System.out
            .println(FnList.ofString().sortBy(Call.methodForInteger("length")).execute(Arrays.asList(arr231)));

    String[] datesStr = new String[] { "12-10-1492", "06-12-1978" };

    List<Calendar> dates = Op.on(datesStr).toList().map(FnString.toCalendar("dd-MM-yyyy")).get();

    System.out.println(Op.on(dates).map(FnCalendar.toStr("yyyy, MMMM dd", new Locale("gl", "ES"))).get());

    Function<Integer, Boolean> afnb1 = new Function<Integer, Boolean>() {

        public Boolean execute(Integer input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };

    Function<Number, Boolean> afnb2 = new Function<Number, Boolean>() {

        public Boolean execute(Number input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };

    Function<Integer, Boolean> afnb = FnBoolean.and(afnb1, afnb2);

    Function<Number, Boolean> bfnb1 = new Function<Number, Boolean>() {
        public Boolean execute(Number input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };
    Function<Integer, Boolean> bfnb2 = new Function<Integer, Boolean>() {
        public Boolean execute(Integer input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };
    Function<Integer, Boolean> bfnb = FnBoolean.and(bfnb1, bfnb2);

    Op.on(231).ifTrue(afnb).get();
    Op.on(231).ifTrue(bfnb).get();

    Op.on(231).ifTrue(FnBoolean.and(afnb1, afnb2)).get();
    Op.on(231).ifTrue(FnBoolean.and(bfnb1, bfnb2)).get();

    Function<Object, Boolean> cfnb1 = new Function<Object, Boolean>() {

        public Boolean execute(Object input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };

    Function<Number, Boolean> cfnb2 = new Function<Number, Boolean>() {

        public Boolean execute(Number input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };
    Function<Number, Boolean> cfnb = FnBoolean.and(cfnb1, cfnb2);

    Function<Number, Boolean> dfnb1 = new Function<Number, Boolean>() {

        public Boolean execute(Number input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };
    Function<Object, Boolean> dfnb2 = new Function<Object, Boolean>() {

        public Boolean execute(Object input, ExecCtx ctx) throws Exception {
            return Boolean.TRUE;
        }
    };
    Function<Number, Boolean> dfnb = FnBoolean.and(dfnb1, dfnb2);

    Op.on(231.2).ifTrue(cfnb).get();
    Op.on(231.1).ifTrue(dfnb).get();

    Op.on(231.2).ifTrue(FnBoolean.and(cfnb1, cfnb2)).get();
    Op.on(231.1).ifTrue(FnBoolean.and(dfnb1, dfnb2)).get();

    Function<Number, Integer> fnz1 = new Function<Number, Integer>() {

        public Integer execute(Number input, ExecCtx ctx) throws Exception {
            // TODO Auto-generated method stub
            return null;
        }
    };

    Function<Integer, Integer> fnn1 = FnFunc.ifTrueThen(Types.INTEGER, FnNumber.greaterThan(2), fnz1);

    Fn.on(Types.INTEGER).exec(FnFunc.ifTrueThen(Types.NUMBER, FnNumber.greaterThan(2), fnz1)).get();

    BigInteger biValue = BigInteger.valueOf(-1256565646);

    System.out.println("Starting value = " + biValue);

    BigInteger biOpResult = Op.on(biValue).exec(FnBigInteger.divideBy(BigInteger.valueOf(23)))
            .exec(FnBigInteger.pow(3)).exec(FnBigInteger.subtract(BigInteger.valueOf(5)))
            .exec(FnBigInteger.abs()).get();

    System.out.println("With op4j:    " + biOpResult);

    BigInteger biNorResult = biValue.divide(BigInteger.valueOf(23)).pow(3).subtract(BigInteger.valueOf(5))
            .abs();

    System.out.println("Without op4j: " + biNorResult);

    BigInteger biOpResult1 = Op.on(biValue).exec(FnBigInteger.divideBy(BigInteger.valueOf(23))).get();

    System.out.println("[1] With op4j:    " + biOpResult1);

    BigInteger biNorResult1 = biValue.divide(BigInteger.valueOf(23));

    System.out.println("[1] Without op4j: " + biNorResult1);

    BigDecimal biOpResult1d = Op.on(new BigDecimal(biValue))
            .exec(FnBigDecimal.divideBy(BigDecimal.valueOf(23.0), RoundingMode.DOWN)).get();

    System.out.println("[1D] With op4j:    " + biOpResult1d);

    BigDecimal biNorResult1d = new BigDecimal(biValue).divide(BigDecimal.valueOf(23.0), RoundingMode.DOWN);

    System.out.println("[1D] Without op4j: " + biNorResult1d);

    System.out
            .println(
                    Op.on(Types.STRING, null)
                            .exec(FnFunc.ifTrueThen(Types.STRING, FnBoolean.or(FnObject.isNull(),
                                    FnBoolean.and(FnObject.isNotNull(),
                                            FnFunc.chain(FnString.toInteger(), FnNumber.greaterThan(100)))),
                                    FnObject.replaceWith("lelo")))
                            .get());

    System.out.println(Arrays.asList(Op.onArrayFor(4, 2).get()));

    System.out.println(Op.on("hello").zipKey(98).get());

    System.out.println(Op.onListFor("en", "en", "es", "gl", "fr")
            .zipAndGroupValues("hello", "goodbye", "hola", "ola", "all").get());

    System.out.println(Op.onListFor("hello", "goodbye", "hola", "ola", "all")
            .zipAndGroupKeys("en", "en", "es", "gl", "fr").get());

    System.out.println(Op.onArrayFor("hello", "goodbye", "hola", "ola", "all")
            .zipAndGroupKeys("en", "en", "es", "gl", "fr").get());

    System.out.println(Op.onMapFor(23, "twenty-three").and(43, "forty-three").and(10, "ten").sort().get());

    System.out.println(Arrays.asList(Op.onArrayFor(1, 2, 1, 2, 2)
            .zipAndGroupValues(Types.STRING, "a", "b", "c", "d", "e").get().get(1)));

    System.out.println(
            Op.on("hello").ifTrue(FnString.notEq("uncapitalizable")).exec(FnString.toUpperCase()).get());
    System.out.println(Op.on("uncapitalizable").ifTrue(FnString.notEq("uncapitalizable"))
            .exec(FnString.toUpperCase()).get());

    Map<String, Integer> agesByName = Op.onListFor(27, 49, 19).zipKeys("John", "Mary", "Derek").get();

    System.out.println(agesByName);

    Map<String, String> capitals = Op
            .onListFor("Spain", "Madrid", "United Kingdom", "London", "France", "Paris").couple().get();

    System.out.println(capitals);

    String date = "06/12/1978";
    Calendar cal = Op.on(date).exec(FnString.toCalendar("dd/MM/yyyy")).get();

    System.out.println(dateFormat.format(cal.getTime()));

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date dt = sdf.parse("06/12/1978");
    Calendar c = Calendar.getInstance();
    c.setTime(dt);
    System.out.println(dateFormat.format(c.getTime()));

    System.out.println(Op.onListFor(2, 12, 42, 5, 9, 24)
            .mapIfTrue(FnNumber.lessOrEqTo(10), FnObject.replaceWith("<"), FnObject.replaceWith(">")).get());

    System.out.println(Op.on("LO E  I N OR! ae").exec(FnString.asciify()).get());
    System.out.println(Op.on("  a  nu NU nu NU ").exec(FnString.asciify()).get());
    System.out.println(Op.on("").exec(FnString.asciify()).get());

    Pair<Integer, Integer> p = Op.on(dt).exec(FnTuple.pairWith(Call.i("getYear"), Get.i("month"))).get();
    System.out.println(p);

    Integer i10 = Op.on(dt).exec(FnTuple.pairWith(Call.i("getYear"), Get.i("month")))
            .exec(FnTuple.getValue1Of(Types.INTEGER)).get();
    System.out.println(i10);

}

From source file:org.openmrs.module.amrsreports.reporting.data.evaluator.BatchedExecutionDataEvaluator.java

@Override
public EvaluatedPersonData evaluate(PersonDataDefinition definition, EvaluationContext context)
        throws EvaluationException {

    PersonDataDefinition def = setDefinition(definition);

    EvaluatedPersonData c = new EvaluatedPersonData(def, context);

    if (context.getBaseCohort() != null && context.getBaseCohort().isEmpty()) {
        return c;
    }/*from  w  ww .  j av  a 2 s  .  c om*/

    Cohort cohort = new Cohort(context.getBaseCohort().getMemberIds());

    // perform pre-actions, return the data if it failed
    if (!doBefore(context, c, cohort))
        return c;

    // create cohort partitions
    int partitionSize = AmrsReportsConstants.DEFAULT_BATCH_SIZE;
    List<Cohort> partitions = new LinkedList<Cohort>();
    List<Integer> ids = new ArrayList<Integer>();
    ids.addAll(cohort.getMemberIds());
    for (int i = 0; i < ids.size(); i += partitionSize) {
        partitions.add(new Cohort(ids.subList(i, i + Math.min(partitionSize, ids.size() - i))));
    }

    log.info("number of partitions: " + partitions.size());

    Map<String, Object> m = getSubstitutions(context);

    String hql = getHQL();

    DataSetQueryService qs = Context.getService(DataSetQueryService.class);

    // calculate for [partition] people at a time
    for (Cohort partition : partitions) {

        m.put("personIds", partition);

        StopWatch timer = new StopWatch();
        timer.start();

        List<Object> queryResult = qs.executeHqlQuery(hql, m);

        timer.stop();
        String timeGetting = timer.toString();
        timer.reset();
        timer.start();

        SortedSetMap<Integer, T> results = new SortedSetMap<Integer, T>();
        results.setSetComparator(getResultsComparator());

        for (Object o : queryResult) {
            Map<String, Object> res = (Map<String, Object>) o;
            T t = renderSingleResult(res);
            results.putInList(t.getPersonId(), t);
        }

        timer.stop();
        String timeLoading = timer.toString();
        timer.reset();
        timer.start();

        for (Integer pId : results.keySet()) {
            c.addData(pId, doExecute(pId, results.get(pId), context));
        }

        Context.flushSession();
        Context.clearSession();

        timer.stop();
        String timeConsuming = timer.toString();

        log.info(String.format("Getting: %s | Loading: %s | Consuming: %s | Patients: %d", timeGetting,
                timeLoading, timeConsuming, partition.size()));
    }

    // perform post-actions, return the data if it failed
    doAfter(context, c);

    return c;
}

From source file:org.openmrs.module.emrmonitor.api.impl.EmrMonitorServiceImpl.java

@Override
public EmrMonitorReport generateEmrMonitorReport() {
    log.debug("Generating EMR monitor report");

    EmrMonitorServer localServer = ensureLocalServer();
    EmrMonitorReport report = new EmrMonitorReport();
    report.setServer(localServer);//from   w w w  .  j ava  2  s .  c  o  m
    report.setDateCreated(new Date());
    report.setStatus(EmrMonitorReport.SubmissionStatus.WAITING_TO_SEND);

    List<String> disabledProducers = EmrMonitorConfig.getDisabledMetricProducers();

    StopWatch sw = new StopWatch();
    for (MetricProducer metricProducer : Context.getRegisteredComponents(MetricProducer.class)) {
        if (metricProducer.isEnabled()) {
            String namespace = metricProducer.getNamespace();
            if (!disabledProducers.contains(namespace)) {
                log.debug("Generating metrics for " + namespace + " ("
                        + metricProducer.getClass().getSimpleName() + ")");
                sw.start();
                Map<String, String> metrics = metricProducer.produceMetrics();
                if (metrics != null) {
                    for (String metricName : metrics.keySet()) {
                        String metricValue = metrics.get(metricName);
                        report.setMetric(namespace + "." + metricName, metricValue);
                        log.debug(metricName + ": " + metricValue);
                    }
                }
                sw.stop();
                log.debug(namespace + " metrics generated in: " + sw.toString());
                sw.reset();
            }
        }
    }

    return saveEmrMonitorReport(report);
}

From source file:org.openmrs.module.pihmalawi.reporting.PerformanceTest.java

@Override
public void performTest() throws Exception {
    HqlQueryBuilder encounterQuery = new HqlQueryBuilder();
    encounterQuery.select("e.encounterId", "e.patient.patientId");
    encounterQuery.from(Encounter.class, "e");
    //encounterQuery.whereLessOrEqualTo("e.encounterId", 10000);

    EncounterEvaluationContext eec = new EncounterEvaluationContext();
    eec.setBaseEncounters(new EncounterIdSet());
    eec.setBaseCohort(new Cohort());

    List<Object[]> l = evaluationService.evaluateToList(encounterQuery, eec);
    for (Object[] row : l) {
        eec.getBaseEncounters().add((Integer) row[0]);
        eec.getBaseCohort().addMember((Integer) row[1]);
    }//from ww  w .  j av a  2s  . c  o  m

    System.out.println("Running a query on " + eec.getBaseEncounters().getSize() + " encounters; "
            + eec.getBaseCohort().size() + " patients");

    HqlQueryBuilder q = new HqlQueryBuilder();
    q.select("e.encounterDatetime");
    q.from(Encounter.class, "e");
    q.whereEncounterIn("e.encounterId", eec);

    System.out.println("Starting evaluation...");
    StopWatch sw = new StopWatch();
    sw.start();
    evaluationService.evaluateToList(q, eec);
    sw.stop();
    System.out.println("Evaluated in: " + sw.toString());
}

From source file:org.openmrs.module.pihmalawi.reporting.reports.ReportManagerTest.java

@Override
public void performTest() throws Exception {
    ReportManagerUtil.setupReport(getReportManager());
    ReportUtil.updateGlobalProperty(ReportingConstants.GLOBAL_PROPERTY_DATA_EVALUATION_BATCH_SIZE, "-1");
    ReportUtil.updateGlobalProperty(ReportingConstants.DEFAULT_LOCALE_GP_NAME, "en");
    //LogManager.getLogger(EvaluationProfiler.class).setLevel(Level.TRACE);

    ReportManager rm = getReportManager();
    ReportDefinition rd = reportDefinitionService.getDefinitionByUuid(rm.getUuid());
    Assert.assertEquals(rm.getName(), rd.getName());
    Assert.assertEquals(rm.getDescription(), rd.getDescription());
    for (ReportDesign design : rm.constructReportDesigns(rd)) {
        ReportDesign dbDesign = reportService.getReportDesignByUuid(design.getUuid());
        Assert.assertEquals(design.getName(), dbDesign.getName());
        Assert.assertEquals(design.getRendererType(), dbDesign.getRendererType());
        Assert.assertEquals(design.getResources().size(), dbDesign.getResources().size());
    }/*from  www .j av a 2s .c  om*/

    EvaluationContext context = getEvaluationContext();
    System.out.println("Running report: " + rd.getName());
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ReportData data = reportDefinitionService.evaluate(rd, context);
    stopWatch.stop();
    System.out.println("Report completed: " + stopWatch.toString());
    Assert.assertTrue(data.getDataSets().size() > 0);
    for (RenderingMode renderingMode : reportService.getRenderingModes(rd)) {
        ReportRenderer renderer = renderingMode.getRenderer();
        if (!(renderer instanceof WebReportRenderer)) {
            String argument = renderingMode.getArgument();
            ReportRequest request = new ReportRequest(
                    new Mapped<ReportDefinition>(rd, context.getParameterValues()), null, renderingMode,
                    ReportRequest.Priority.HIGHEST, null);
            File outFile = new File(SystemUtils.getJavaIoTmpDir(), renderer.getFilename(request));
            FileOutputStream fos = new FileOutputStream(outFile);
            renderer.render(data, argument, fos);
            fos.close();
        }
    }
    if (enableReportOutput()) {
        for (String dsName : data.getDataSets().keySet()) {
            System.out.println(dsName);
            System.out.println("---------------------------------");
            DataSetUtil.printDataSet(data.getDataSets().get(dsName), System.out);
        }
    }
}

From source file:org.openmrs.module.reporting.data.patient.service.PatientDataServiceImpl.java

@Override
protected Evaluated<PatientDataDefinition> executeEvaluator(
        DefinitionEvaluator<PatientDataDefinition> evaluator, PatientDataDefinition definition,
        EvaluationContext context) throws EvaluationException {

    EvaluatedPatientData ret = new EvaluatedPatientData(definition, context);
    int batchSize = ReportingConstants.GLOBAL_PROPERTY_DATA_EVALUATION_BATCH_SIZE();

    // Do not evaluate in batches if no base cohort is supplied, or no batch size is specified
    if (context.getBaseCohort() == null || batchSize <= 0 || context.getBaseCohort().size() <= batchSize) {
        return super.executeEvaluator(evaluator, definition, context);
    }//  w w w.  ja va 2s .  c  om

    if (context.getBaseCohort().size() > 0) {

        List<Cohort> batches = new ArrayList<Cohort>();
        List<Integer> ids = new ArrayList<Integer>(context.getBaseCohort().getMemberIds());
        for (int i = 0; i < ids.size(); i += batchSize) {
            batches.add(new Cohort(ids.subList(i, i + Math.min(batchSize, ids.size() - i))));
        }
        log.info("Number of batches to execute: " + batches.size());

        // Evaluate each batch
        for (Cohort batchCohort : batches) {
            EvaluationContext batchContext = context.shallowCopy();
            batchContext.setBaseCohort(batchCohort);
            batchContext.clearCache(); // Setting base cohort should do this, but just to be sure

            StopWatch timer = new StopWatch();
            timer.start();

            EvaluatedPatientData batchData = (EvaluatedPatientData) super.executeEvaluator(evaluator,
                    definition, batchContext);
            ret.getData().putAll(batchData.getData());

            timer.stop();
            log.debug("Evaluated batch: " + timer.toString());
            log.debug("Number of running data evaluated: " + ret.getData().size());

            timer.reset();

            Context.flushSession();
            Context.clearSession();
        }
    }
    return ret;
}

From source file:org.openmrs.module.reporting.dataset.definition.evaluator.EncounterDataSetEvaluator.java

/**
 * @see DataSetEvaluator#evaluate(DataSetDefinition, EvaluationContext)
 *//*from  w ww  . j  a  v  a 2s.  c  om*/
@SuppressWarnings("unchecked")
public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context)
        throws EvaluationException {

    EncounterDataSetDefinition dsd = (EncounterDataSetDefinition) dataSetDefinition;
    context = ObjectUtil.nvl(context, new EvaluationContext());

    SimpleDataSet dataSet = new SimpleDataSet(dsd, context);
    dataSet.setSortCriteria(dsd.getSortCriteria());

    // Construct an EncounterEvaluationContext based on the encounter filter
    EncounterIdSet r = null;
    if (dsd.getRowFilters() != null) {
        for (Mapped<? extends EncounterQuery> q : dsd.getRowFilters()) {
            EncounterIdSet s = Context.getService(EncounterQueryService.class).evaluate(q, context);
            r = QueryUtil.intersectNonNull(r, s);
        }
    }
    if (r == null) {
        r = Context.getService(EncounterQueryService.class).evaluate(new AllEncounterQuery(), context);
    }
    EncounterEvaluationContext eec = new EncounterEvaluationContext(context, r);
    eec.setBaseCohort(null); // We can do this because the encounterIdSet is already limited by these

    // Evaluate each specified ColumnDefinition for all of the included rows and add these to the dataset
    for (RowPerObjectColumnDefinition cd : dsd.getColumnDefinitions()) {

        if (log.isDebugEnabled()) {
            log.debug("Evaluating column: " + cd.getName());
            log.debug("With Data Definition: "
                    + DefinitionUtil.format(cd.getDataDefinition().getParameterizable()));
            log.debug("With Mappings: " + cd.getDataDefinition().getParameterMappings());
            log.debug("With Parameters: " + eec.getParameterValues());
        }

        StopWatch sw = new StopWatch();
        sw.start();

        MappedData<? extends EncounterDataDefinition> dataDef = (MappedData<? extends EncounterDataDefinition>) cd
                .getDataDefinition();
        EvaluatedEncounterData data = Context.getService(EncounterDataService.class).evaluate(dataDef, eec);

        DataSetColumn column = new DataSetColumn(cd.getName(), cd.getName(),
                dataDef.getParameterizable().getDataType()); // TODO: Support One-Many column definition to column

        for (Integer id : r.getMemberIds()) {
            Object val = data.getData().get(id);
            val = DataUtil.convertData(val, dataDef.getConverters());
            dataSet.addColumnValue(id, column, val);
        }

        sw.stop();
        if (log.isDebugEnabled()) {
            log.debug("Added encounter column: " + sw.toString());
        }

    }

    return dataSet;
}

From source file:org.openmrs.module.reporting.dataset.definition.evaluator.PatientDataSetEvaluator.java

/**
 * @see DataSetEvaluator#evaluate(DataSetDefinition, EvaluationContext)
 *//* w  w w.  j  a va  2 s . com*/
@SuppressWarnings("unchecked")
public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context)
        throws EvaluationException {

    PatientDataSetDefinition dsd = (PatientDataSetDefinition) dataSetDefinition;
    context = ObjectUtil.nvl(context, new EvaluationContext());

    SimpleDataSet dataSet = new SimpleDataSet(dsd, context);
    dataSet.setSortCriteria(dsd.getSortCriteria());

    // Construct a new EvaluationContext based on the passed filters
    Cohort c = context.getBaseCohort();
    if (dsd.getRowFilters() != null) {
        for (Mapped<? extends CohortDefinition> q : dsd.getRowFilters()) {
            Cohort s = Context.getService(CohortDefinitionService.class).evaluate(q, context);
            c = CohortUtil.intersectNonNull(c, s);
        }
    }
    if (c == null) {
        c = Context.getService(CohortDefinitionService.class).evaluate(new AllPatientsCohortDefinition(),
                context);
    }

    EvaluationContext ec = context.shallowCopy();
    if (!CohortUtil.areEqual(ec.getBaseCohort(), c)) {
        ec.setBaseCohort(c);
    }

    // Evaluate each specified ColumnDefinition for all of the included rows and add these to the dataset
    for (RowPerObjectColumnDefinition cd : dsd.getColumnDefinitions()) {

        if (log.isDebugEnabled()) {
            log.debug("Evaluating column: " + cd.getName());
            log.debug("With Data Definition: "
                    + DefinitionUtil.format(cd.getDataDefinition().getParameterizable()));
            log.debug("With Mappings: " + cd.getDataDefinition().getParameterMappings());
            log.debug("With Parameters: " + ec.getParameterValues());
        }
        StopWatch sw = new StopWatch();
        sw.start();

        MappedData<? extends PatientDataDefinition> dataDef = (MappedData<? extends PatientDataDefinition>) cd
                .getDataDefinition();
        EvaluatedPatientData data = Context.getService(PatientDataService.class).evaluate(dataDef, ec);

        for (Integer id : c.getMemberIds()) {
            for (DataSetColumn column : cd.getDataSetColumns()) {
                Object val = data.getData().get(id);
                val = DataUtil.convertData(val, dataDef.getConverters());
                dataSet.addColumnValue(id, column, val);
            }
        }

        sw.stop();
        if (log.isDebugEnabled()) {
            log.debug("Evaluated column. Duration: " + sw.toString());
        }
    }

    return dataSet;
}

From source file:org.openmrs.module.reporting.dataset.definition.evaluator.VisitDataSetEvaluator.java

/**
 * @see DataSetEvaluator#evaluate(org.openmrs.module.reporting.dataset.definition.DataSetDefinition, org.openmrs.module.reporting.evaluation.EvaluationContext)
 *///from www. j  a  v a  2s . c om
@SuppressWarnings("unchecked")
public DataSet evaluate(DataSetDefinition dataSetDefinition, EvaluationContext context)
        throws EvaluationException {

    VisitDataSetDefinition dsd = (VisitDataSetDefinition) dataSetDefinition;
    context = ObjectUtil.nvl(context, new EvaluationContext());

    SimpleDataSet dataSet = new SimpleDataSet(dsd, context);
    dataSet.setSortCriteria(dsd.getSortCriteria());

    // Construct a VisitEvaluationContext based on the visit filter
    VisitIdSet r = null;
    if (dsd.getRowFilters() != null) {
        for (Mapped<? extends VisitQuery> q : dsd.getRowFilters()) {
            VisitIdSet s = Context.getService(VisitQueryService.class).evaluate(q, context);
            r = QueryUtil.intersectNonNull(r, s);
        }
    }
    if (r == null) {
        r = Context.getService(VisitQueryService.class).evaluate(new AllVisitQuery(), context);
    }
    VisitEvaluationContext vec = new VisitEvaluationContext(context, r);
    vec.setBaseCohort(null); // We can do this because the visitIdSet is already limited by these

    // Evaluate each specified ColumnDefinition for all of the included rows and add these to the dataset
    for (RowPerObjectColumnDefinition cd : dsd.getColumnDefinitions()) {

        if (log.isDebugEnabled()) {
            log.debug("Evaluating column: " + cd.getName());
            log.debug("With Data Definition: "
                    + DefinitionUtil.format(cd.getDataDefinition().getParameterizable()));
            log.debug("With Mappings: " + cd.getDataDefinition().getParameterMappings());
            log.debug("With Parameters: " + vec.getParameterValues());
        }

        StopWatch sw = new StopWatch();
        sw.start();

        MappedData<? extends VisitDataDefinition> dataDef = (MappedData<? extends VisitDataDefinition>) cd
                .getDataDefinition();
        EvaluatedVisitData data = Context.getService(VisitDataService.class).evaluate(dataDef, vec);

        DataSetColumn column = new DataSetColumn(cd.getName(), cd.getName(),
                dataDef.getParameterizable().getDataType()); // TODO: Support One-Many column definition to column

        for (Integer id : r.getMemberIds()) {
            Object val = data.getData().get(id);
            val = DataUtil.convertData(val, dataDef.getConverters());
            dataSet.addColumnValue(id, column, val);
        }

        sw.stop();
        if (log.isDebugEnabled()) {
            log.debug("Added encounter column: " + sw.toString());
        }

    }

    return dataSet;
}