Example usage for java.math RoundingMode CEILING

List of usage examples for java.math RoundingMode CEILING

Introduction

In this page you can find the example usage for java.math RoundingMode CEILING.

Prototype

RoundingMode CEILING

To view the source code for java.math RoundingMode CEILING.

Click Source Link

Document

Rounding mode to round towards positive infinity.

Usage

From source file:org.whispersystems.bithub.controllers.GithubController.java

private String getCommitCommentStringForPayment(BigDecimal payment, BigDecimal exchangeRate) {
    if (isViablePaymentAmount(payment)) {
        BigDecimal paymentUsd = payment.multiply(exchangeRate).setScale(2, RoundingMode.CEILING);
        return "Thanks! BitHub has sent payment of  $" + paymentUsd.toPlainString() + "USD for this commit.";
    } else {//w w  w .  j a  v  a 2s  .  com
        return "Thanks! Unfortunately our BitHub balance is $0.00, so no payout can be made.";
    }
}

From source file:uk.ac.kcl.at.ElasticGazetteerAcceptanceTest.java

@Test
public void deidentificationPerformanceTest() {
    dbmsTestUtils.createBasicInputTable();
    dbmsTestUtils.createBasicOutputTable();
    dbmsTestUtils.createDeIdInputTable();
    List<Mutant> mutants = testUtils.insertTestDataForDeidentification(env.getProperty("tblIdentifiers"),
            env.getProperty("tblInputDocs"), mutatortype, true);

    int totalTruePositives = 0;
    int totalFalsePositives = 0;
    int totalFalseNegatives = 0;

    for (Mutant mutant : mutants) {
        Set<Pattern> mutatedPatterns = new HashSet<>();
        mutant.setDeidentifiedString(elasticGazetteerService.deIdentifyString(mutant.getFinalText(),
                String.valueOf(mutant.getDocumentid())));
        Set<String> set = new HashSet<>(mutant.getOutputTokens());
        mutatedPatterns.addAll(/*from ww  w.  j  ava2 s . c  om*/
                set.stream().map(string -> Pattern.compile(Pattern.quote(string), Pattern.CASE_INSENSITIVE))
                        .collect(Collectors.toSet()));
        List<MatchResult> results = new ArrayList<>();
        for (Pattern pattern : mutatedPatterns) {
            Matcher matcher = pattern.matcher(mutant.getFinalText());
            while (matcher.find()) {
                results.add(matcher.toMatchResult());
            }
        }

        int truePositives = getTruePositiveTokenCount(mutant);
        int falsePositives = getFalsePositiveTokenCount(mutant);
        int falseNegatives = getFalseNegativeTokenCount(mutant);

        System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives
                + " unmasked identifiers from a total of " + (falseNegatives + truePositives));
        System.out.println("Doc ID " + mutant.getDocumentid() + " has " + falsePositives
                + " inaccurately masked tokens from a total of " + (falsePositives + truePositives));
        System.out.println("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives);
        System.out.println("Doc ID precision " + calcPrecision(falsePositives, truePositives));
        System.out.println("Doc ID recall " + calcRecall(falseNegatives, truePositives));
        System.out.println(mutant.getDeidentifiedString());
        System.out.println(mutant.getFinalText());
        System.out.println(mutant.getInputTokens());
        System.out.println(mutant.getOutputTokens());
        System.out.println();
        if (env.getProperty("elasticgazetteerTestOutput") != null) {
            try {
                try (BufferedWriter bw = new BufferedWriter(
                        new FileWriter(new File(env.getProperty("elasticgazetteerTestOutput") + File.separator
                                + mutant.getDocumentid())))) {
                    bw.write("Doc ID " + mutant.getDocumentid() + " has " + falseNegatives
                            + " unmasked identifiers from a total of " + (falseNegatives + truePositives));
                    bw.newLine();
                    bw.write("Doc ID " + mutant.getDocumentid() + " has " + falsePositives
                            + " inaccurately masked tokens from a total of "
                            + (falsePositives + truePositives));
                    bw.newLine();
                    bw.write("TP: " + truePositives + " FP: " + falsePositives + " FN: " + falseNegatives);
                    bw.newLine();
                    bw.write("Doc ID precision " + calcPrecision(falsePositives, truePositives));
                    bw.newLine();
                    bw.write("Doc ID recall " + calcRecall(falseNegatives, truePositives));
                    bw.newLine();
                    bw.write(mutant.getDeidentifiedString());
                    bw.newLine();
                    bw.write(mutant.getFinalText());
                    bw.newLine();
                    bw.write(mutant.getInputTokens().toString());
                    bw.newLine();
                    bw.write(mutant.getOutputTokens().toString());

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

        totalTruePositives += truePositives;
        totalFalsePositives += falsePositives;
        totalFalseNegatives += falseNegatives;
    }
    DecimalFormat df = new DecimalFormat("#.#");
    df.setRoundingMode(RoundingMode.CEILING);

    System.out.println();
    System.out.println();
    System.out.println("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: "
            + totalFalseNegatives);
    System.out.println("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives));
    System.out.println("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives));
    System.out.println(totalTruePositives + " & " + totalFalsePositives + " & " + totalFalseNegatives + " & "
            + df.format(calcPrecision(totalFalsePositives, totalTruePositives)) + " & "
            + df.format(calcRecall(totalFalseNegatives, totalTruePositives)) + " \\\\");

    if (env.getProperty("elasticgazetteerTestOutput") != null) {
        try {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(
                    new File(env.getProperty("elasticgazetteerTestOutput") + File.separator + "summary")))) {
                bw.write("THIS RUN TP: " + totalTruePositives + " FP: " + totalFalsePositives + " FN: "
                        + totalFalseNegatives);
                bw.newLine();
                bw.write("Doc ID precision " + calcPrecision(totalFalsePositives, totalTruePositives));
                bw.newLine();
                bw.write("Doc ID recall " + calcRecall(totalFalseNegatives, totalTruePositives));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:science.atlarge.graphalytics.powergraph.PowergraphPlatform.java

@Override
public BenchmarkMetrics finalize(RunSpecification runSpecification) {
    stopPlatformLogging();//from  ww  w.  j av a 2 s .com
    BenchmarkRunSetup benchmarkRunSetup = runSpecification.getBenchmarkRunSetup();
    BenchmarkRun benchmarkRun = runSpecification.getBenchmarkRun();

    Path platformLogPath = benchmarkRunSetup.getLogDir().resolve("platform");

    final List<Double> superstepTimes = new ArrayList<>();

    try {
        Files.walkFileTree(platformLogPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String logs = FileUtil.readFile(file);
                for (String line : logs.split("\n")) {
                    if (line.contains("- run algorithm:")) {
                        Pattern regex = Pattern.compile(".* - run algorithm: ([+-]?([0-9]*[.])?[0-9]+) sec.*");
                        Matcher matcher = regex.matcher(line);
                        matcher.find();
                        superstepTimes.add(Double.parseDouble(matcher.group(1)));
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (superstepTimes.size() != 0) {
        Double procTime = 0.0;
        for (Double superstepTime : superstepTimes) {
            procTime += superstepTime;
        }

        BenchmarkMetrics metrics = new BenchmarkMetrics();
        BigDecimal procTimeS = (new BigDecimal(procTime)).setScale(3, RoundingMode.CEILING);
        metrics.setProcessingTime(new BenchmarkMetric(procTimeS, "s"));

        return metrics;
    } else {
        LOG.error("Failed to find any metrics regarding superstep runtime.");
        return new BenchmarkMetrics();
    }
}

From source file:org.egov.ptis.repository.dashboard.RevenueDashboardRepository.java

public List<Map<String, Object>> getWardwisePerformanceTab(final String zoneName) {
    final SQLQuery overAllQry = getQuery("revenue.ptis.wardwise.overall.performance");
    overAllQry.setParameter("zoneName", zoneName);
    final List<Object[]> overAllData = overAllQry.list();
    final Map<String, Map<String, Object>> revenueDataHolder = new HashMap<String, Map<String, Object>>();
    for (final Object[] revenueObj : overAllData) {
        final Map<String, Object> revnData = new HashMap<String, Object>();
        revnData.put("ward", String.valueOf(revenueObj[0]));
        final BigDecimal collectionPerc = (BigDecimal) revenueObj[2];
        revnData.put("collectionPerc", collectionPerc != null ? collectionPerc.doubleValue() : "0");
        revenueDataHolder.put(String.valueOf(revenueObj[0]), revnData);
    }//from  w w w . j  a v a  2s . com

    final SQLQuery monthlyQry = getQuery("revenue.ptis.wardwise.monthly.performance");
    monthlyQry.setParameter("zoneName", zoneName);
    final List<Object[]> monthlyData = monthlyQry.list();
    for (final Object[] revenueObj : monthlyData) {
        final Map<String, Object> revnData = revenueDataHolder.get(String.valueOf(revenueObj[0]));
        final BigDecimal amtTargeted = (BigDecimal) revenueObj[1];
        revnData.put("amtTargeted", amtTargeted != null ? amtTargeted.doubleValue() : "0");
        final BigDecimal amt_collectd = (BigDecimal) revenueObj[2];
        revnData.put("amt_collectd", amt_collectd != null ? amt_collectd.doubleValue() : "0");
        final BigDecimal percCollections = (BigDecimal) revenueObj[3];
        revnData.put("percCollections",
                percCollections != null ? percCollections.setScale(2, RoundingMode.CEILING).doubleValue()
                        : "0");
    }

    final List<Map<String, Object>> revenueAggrData = new ArrayList<Map<String, Object>>(
            revenueDataHolder.values());

    // SORT BY WARDWISE MONTHLY COLLECTION %
    sortData(revenueAggrData, "percCollections");

    // ASSIGN MONTHLY RANK BASED ON SORT ORDER
    assignRank(revenueAggrData, "rank");

    // SORT BY WARDWISE OVERALL COLLECTION %
    sortData(revenueAggrData, "collectionPerc");

    // ASSIGN OVERALL RANK BASED ON SORT ORDER
    assignRank(revenueAggrData, "overallrank");

    return revenueAggrData;
}

From source file:org.openmrs.module.pharmacyapi.api.prescription.util.PrescriptionUtils.java

public Double calculateDrugQuantity(final DrugOrder drugOrder) {
    final int durationUnitsDays = MappedDurationUnits.getDurationDays(drugOrder.getDurationUnits().getUuid());
    double quantity = drugOrder.getDose() * drugOrder.getDuration() * durationUnitsDays
            * drugOrder.getFrequency().getFrequencyPerDay();
    return BigDecimal.valueOf(quantity).setScale(0, RoundingMode.CEILING).doubleValue();
}

From source file:com.vsthost.rnd.commons.math.ext.linear.DMatrixUtils.java

/**
 * Returns the UP rounded value of the given value for the given steps.
 *
 * @param value The original value to be rounded.
 * @param steps The steps./*from   w  w  w .j  a v a2s  . com*/
 * @return The UP rounded value of the given value for the given steps.
 */
public static BigDecimal roundUpTo(double value, double steps) {
    final BigDecimal bValue = BigDecimal.valueOf(value);
    final BigDecimal bSteps = BigDecimal.valueOf(steps);

    if (Objects.equals(bSteps, BigDecimal.ZERO)) {
        return bValue;
    } else {
        return bValue.divide(bSteps, 0, RoundingMode.CEILING).multiply(bSteps);
    }
}

From source file:org.op4j.MiscTest.java

@Test
public void test() throws Exception {

    final StopWatch watch = new StopWatch();
    watch.start();/*from   www .ja v  a  2  s  .  c  om*/

    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:com.repay.android.adddebt.AddDebtActivity.java

private void submitToDB() {
    try {//from   w  w  w. j  a v a  2s .  c  o  m
        if (mSelectedFriends.size() == 0) {
            throw new NullPointerException();

        } else if (mSelectedFriends.size() == 1) {
            BigDecimal latestAmount = new BigDecimal(mAmount.toString());
            if (mNegativeDebt) {
                latestAmount = latestAmount.negate();
            }
            if (mSplitAmount) {
                latestAmount = latestAmount.divide(BigDecimal.valueOf(2));
            }
            mDB.addDebt(mSelectedFriends.get(0).getRepayID(), latestAmount, mDescription);
            mSelectedFriends.get(0).setDebt(mSelectedFriends.get(0).getDebt().add(latestAmount));
            mDB.updateFriendRecord(mSelectedFriends.get(0));

        } else if (mSelectedFriends.size() > 1) {
            BigDecimal debtPerPerson;
            if (mSplitAmount) {
                int numOfPeeps = mSelectedFriends.size();
                Log.i(TAG, Integer.toString(numOfPeeps) + " people selected");
                numOfPeeps += (mInclMe) ? 1 : 0; // If is including me then add me into this
                Log.i(TAG, "isIncludingMe=" + Boolean.toString(mInclMe));
                debtPerPerson = new BigDecimal(mAmount.toString());
                debtPerPerson = debtPerPerson.divide(new BigDecimal(numOfPeeps), RoundingMode.CEILING);
            } else {
                debtPerPerson = new BigDecimal(mAmount.toString());
            }
            if (mNegativeDebt) {
                debtPerPerson = debtPerPerson.negate();
            }
            for (int i = 0; i <= mSelectedFriends.size() - 1; i++) {
                mDB.addDebt(mSelectedFriends.get(i).getRepayID(), debtPerPerson, mDescription);
                mSelectedFriends.get(i).setDebt(mSelectedFriends.get(i).getDebt().add(debtPerPerson));
                mDB.updateFriendRecord(mSelectedFriends.get(i));
            }
        }
        requestBackup();
        finish();
    } catch (SQLException e) {
        Toast.makeText(this, "Database Error", Toast.LENGTH_SHORT).show();
    } catch (NullPointerException e) {
        Toast.makeText(this, "Select a person and enter an amount first!", Toast.LENGTH_SHORT).show();
    } catch (NumberFormatException e) {
        Toast.makeText(this, "Please enter a valid amount!", Toast.LENGTH_SHORT).show();
    } catch (ArithmeticException e) {
        Toast.makeText(this, "You can't divide this number between this many people", Toast.LENGTH_SHORT)
                .show();
    }
}

From source file:org.mifos.config.AccountingRules.java

private static RoundingMode getRoundingModeFromString(String modeStr, String type,
        RoundingMode defaultRoundingMode) {
    if (StringUtils.isBlank(modeStr)) {
        return defaultRoundingMode;
    }/*ww  w .  j  a  v a2  s .  com*/
    RoundingMode mode = null;
    if (modeStr.equals("FLOOR")) {
        mode = RoundingMode.FLOOR;
    } else if (modeStr.equals("CEILING")) {
        mode = RoundingMode.CEILING;
    } else if (modeStr.equals("HALF_UP")) {
        mode = RoundingMode.HALF_UP;
    } else {
        throw new RuntimeException(
                type + " defined in the config file is not CEILING, FLOOR, HALF_UP. It is " + modeStr);
    }
    return mode;
}

From source file:org.openmrs.module.billing.web.controller.billingqueuedia.BillingService.java

@RequestMapping(value = "/module/billing/orderStoreSave.form", method = RequestMethod.POST)
public String billSaveOrder(@RequestParam("patientId") Integer patientId,
        @RequestParam(value = "refDocId", required = false) Integer refDocId,
        @RequestParam(value = "refMarId", required = false) Integer refMarId,
        @RequestParam(value = "orderId", required = false) Integer orderId,
        @RequestParam(value = "refRmpId", required = false) Integer refRmpId,
        @RequestParam(value = "dDate", required = false) String dDate,
        @RequestParam(value = "dTime", required = false) String dTime,
        @RequestParam(value = "rem", required = false) String remarks,
        //  @RequestParam(value = "discount", required = false) BigDecimal discount,
        @RequestParam(value = "discount", required = false) String discount,
        @RequestParam("indCount") Integer indCount,
        @RequestParam(value = "encounterId", required = false) String encounterId, HttpServletRequest request,
        Model model) throws ParseException, Exception {

    Patient patient = Context.getPatientService().getPatient(patientId);

    MedisunService ms = Context.getService(MedisunService.class);
    org.openmrs.module.hospitalcore.BillingService billingService = Context
            .getService(org.openmrs.module.hospitalcore.BillingService.class);

    //Date birthday = patient.getBirthdate();
    // model.addAttribute("age", PatientUtils.estimateAge(birthday));
    String fullPaid = request.getParameter("paid");
    String fullFree = request.getParameter("free");
    String freeReason = request.getParameter("freeReason");
    BigDecimal doctorGivenPer = NumberUtils.createBigDecimal(request.getParameter("docGivPer"));
    BigDecimal p = new BigDecimal("0.00");
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date deDate = null;//from  w  ww.  j ava  2  s .  c  o m

    if (StringUtils.isNotBlank(dDate)) {
        deDate = sdf.parse(dDate);
    }
    //        System.out.println("***********ddddd"+doctorGivenPer);
    //        if (doctorGivenPer == null) {
    //            doctorGivenPer=p;
    //        }
    //        else{
    //            doctorGivenPer=doctorGivenPer;
    //        }
    //                
    DiaBillingQueue dbq = ms.getDiaBillingQueue(orderId);

    DiaReceipt dr = new DiaReceipt();
    dr.setPaidDate(new Date());
    dr.setDeliveryDate(deDate);
    dr.setDeliveryTime(dTime);
    dr.setServiceId(orderId);
    dr.setDoctorGiven(doctorGivenPer); //
    ms.saveDiaReceipt(dr);

    User user = Context.getAuthenticatedUser();

    BillableService service;

    BigDecimal totalBill = NumberUtils.createBigDecimal(request.getParameter("totalBill"));
    BigDecimal netAmount = NumberUtils.createBigDecimal(request.getParameter("netamount"));

    BigDecimal paidAmount = NumberUtils.createBigDecimal(request.getParameter("paidamount"));
    BigDecimal payableAmount = NumberUtils.createBigDecimal(request.getParameter("payableamount"));
    BigDecimal dueAmount = NumberUtils.createBigDecimal(request.getParameter("dueamount"));
    BigDecimal discountAmount = NumberUtils.createBigDecimal(request.getParameter("discountamount"));
    BigDecimal unitPrice = NumberUtils.createBigDecimal(request.getParameter("unitprice"));
    // BigDecimal discount = NumberUtils.createBigDecimal(request.getParameter("discount"));

    if (paidAmount == null) {
        paidAmount = p;
    } else {
        paidAmount = paidAmount;
    }

    String due = null;
    boolean status;
    if ((StringUtils.equals(fullPaid, "1")) && (dueAmount.signum() < 1)) {
        due = "PAID";
        status = false;
        totalBill = totalBill;
    } else if ((StringUtils.equals(fullPaid, null)) && (StringUtils.equals(fullFree, null))
            && (dueAmount.signum() < 1)) {
        due = "PAID";
        status = false;
        totalBill = totalBill;
    } else if ((!StringUtils.equalsIgnoreCase(fullFree, null))) {
        due = "FREE";
        status = true;
        totalBill = p;
    } else {
        due = "DUE";
        status = false;
        totalBill = totalBill;
    }

    DiaPatientServiceBill dpsb = new DiaPatientServiceBill();
    dpsb.setPatient(patient);
    dpsb.setCreatedDate(new Date());
    dpsb.setCreator(user);
    dpsb.setAmount(netAmount);
    dpsb.setPrinted(Boolean.FALSE);
    dpsb.setReceipt(dr);
    dpsb.setVoided(Boolean.FALSE);
    dpsb.setActualAmount(totalBill); /// if free actual amount is 0.00
    dpsb.setDueAmount(dueAmount);
    dpsb.setBillingStatus(due);
    dpsb.setRefDocId(refDocId);
    dpsb.setRefMarId(refMarId);
    dpsb.setRefRmpId(refRmpId);
    dpsb.setComment(remarks);
    dpsb.setDiscountAmount(discountAmount);
    dpsb.setFreeReason(freeReason);
    //if (paidAmount.signum() > 0) {
    dpsb = ms.saveDiaPatientServiceBill(dpsb);
    //}

    // if (dpsb != null && dpsb.getBillId() != null ) {
    if (dpsb != null && dpsb.getBillId() != null && orderId != 0) {
        ms.removeDiaBillingQueue(dbq);
    }
    model.addAttribute("billId", dpsb.getBillId());
    model.addAttribute("orderId", orderId);
    model.addAttribute("refDocId", refDocId);
    model.addAttribute("refRmpId", refRmpId);
    model.addAttribute("paid", paidAmount);
    model.addAttribute("dDate", dDate);
    model.addAttribute("dTime", dTime);

    DiaPatientServiceBillCollect dBillColl = new DiaPatientServiceBillCollect();
    dBillColl.setPatientId(patientId);
    dBillColl.setDiaPatientServiceBill(dpsb);
    dBillColl.setUser(user);
    dBillColl.setCreatedDate(new Date());
    dBillColl.setActualAmount(totalBill);
    dBillColl.setPaidAmount(paidAmount);
    dBillColl.setPayableAmount(netAmount);
    dBillColl.setDueAmount(dueAmount);
    dBillColl.setDiscountAmount(discountAmount);
    dBillColl.setDuePaidStatus(status);
    dBillColl.setDuePaid(0);
    //if (paidAmount.signum() > 0) {
    ms.saveDiaPatientServiceBillCollect(dBillColl);
    //}

    String sername = null;
    BigDecimal totCom = BigDecimal.ZERO;
    BigDecimal servicePrice = BigDecimal.ZERO;

    for (Integer i = 1; i <= indCount; i++) {

        String servicename = request.getParameter("service");
        unitPrice = NumberUtils.createBigDecimal(request.getParameter(i.toString() + "unitprice")); // Quantity * unitPrice
        BigDecimal serviceprice = NumberUtils
                .createBigDecimal(request.getParameter(i.toString() + "serviceprice")); // Unit Price

        Integer qty = NumberUtils.createInteger(request.getParameter(i.toString() + "servicequantity")); // Quantity
        servicename = request.getParameter(i.toString() + "service");
        service = billingService.getServiceByConceptName(servicename);

        if (((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678")))) {
            sername = servicename + "," + sername; // for commison

            servicePrice = servicePrice.add(unitPrice);
        }

        DiaPatientServiceBillItem dBillItem = new DiaPatientServiceBillItem();
        dBillItem.setService(service);
        dBillItem.setDiaPatientServiceBill(dpsb);
        dBillItem.setUnitPrice(serviceprice);
        dBillItem.setAmount(unitPrice);
        dBillItem.setQuantity(qty);
        dBillItem.setName(servicename);
        dBillItem.setCreatedDate(new Date());
        dBillItem.setCreator(user.getId());
        dBillItem.setVoided(Boolean.FALSE);
        dBillItem.setActualAmount(unitPrice);
        // if (paidAmount.signum() > 0) {
        ms.saveDiaPatientServiceBillItem(dBillItem);
        //}

        BigDecimal ind = NumberUtils.createBigDecimal(indCount.toString());
        BigDecimal da = discountAmount.divide(ind, 2, RoundingMode.CEILING);

        BigDecimal oneHundred = new BigDecimal(100);

        BigDecimal le = null;
        if (!StringUtils.isBlank(discount)) {
            BigDecimal dis;
            dis = new BigDecimal(discount);
            BigDecimal less = (unitPrice.multiply(dis)).divide(oneHundred, 0, RoundingMode.HALF_EVEN);
            le = less;
        } else {
            le = new BigDecimal(0);
        }

        //BigDecimal less = (unitPrice.multiply(discount)).divide(oneHundred, 0, RoundingMode.HALF_EVEN);
        if (dpsb.getBillingStatus() == "PAID") {
            if ((!StringUtils.equalsIgnoreCase(service.getCategory().getId().toString(), "5678"))) {
                DiaCommissionCal diaComCal = new DiaCommissionCal();
                diaComCal.setDiaPatientServiceBill(dpsb);
                diaComCal.setPatient(patient);
                diaComCal.setServiceName(service.getName());
                diaComCal.setServiceId(service.getServiceId());
                diaComCal.setServicePrice(serviceprice);
                //diaComCal.setLessAmount(discountAmount);
                diaComCal.setLessAmount(le);
                diaComCal.setCommission(service.getCommission());
                diaComCal.setCreatedDate(new Date());
                diaComCal.setCreator(user.getId());
                diaComCal.setRefId(dpsb.getRefDocId());
                diaComCal.setRefRmpId(dpsb.getRefRmpId());
                diaComCal.setHsStatus(Boolean.FALSE);
                ms.saveDiaComCal(diaComCal);
            }
        }

        DiaLabSampleid dls = new DiaLabSampleid();
        dls.setPatient(patient);
        dls.setDiaPatientServiceBill(dpsb);
        dls.setSampleId(generateBarcode());
        ms.saveDiaLabSam(dls);

    }

    if (sername != null && dpsb.getBillingStatus() == "PAID") {
        sername = sername.replace(",null", "");

        DiaCommissionCalAll diaAll = new DiaCommissionCalAll();
        diaAll.setDiaPatientServiceBill(dpsb);
        diaAll.setPatient(patient);
        //diaAll.setServiceName(sername);
        diaAll.setServicePrice(servicePrice);
        diaAll.setLessAmount(discountAmount);
        diaAll.setComAmount(totCom);
        diaAll.setCreatedDate(new Date());
        diaAll.setCreator(Context.getAuthenticatedUser().getId());
        diaAll.setRefId(refDocId);
        diaAll.setRefRmp(refRmpId);
        diaAll.setRefMar(refMarId);
        ms.saveDiaComAll(diaAll);
    }

    //// Generate Patient Id Barcode4j
    Code128Bean cod = new Code128Bean();
    final int reso = 128;
    cod.setModuleWidth(UnitConv.in2mm(1.0f / reso)); //makes the narrow bar 
    //width exactly one pixel
    cod.setHeight(10);
    cod.setFontSize(3);
    cod.setFontName("Times New Roman");
    // cod.doQuietZone(true);
    cod.getBarWidth(2);
    // bean.setVerticalQuietZone(1);
    cod.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);

    File outputFilePatId = new File(
            request.getSession().getServletContext().getRealPath("/barcode/" + patient.getId() + ".png"));
    // File outputFilePatId = new File("C:\\tomcat6\\webapps\\MEDISUN_HEALTH_CARE_V2_Final\\barcode/" + patient.getId() + ".png"); //Mostofa bhi

    OutputStream out1 = new FileOutputStream(outputFilePatId);
    try {
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(out1, "image/x-png", reso,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        cod.generateBarcode(canvas, patient.getPatientIdentifier().getIdentifier());

        canvas.finish();
    } finally {
        out1.close();
    }

    //// Generate Bill Id Barcode4j
    Code128Bean codBil = new Code128Bean();
    final int resou = 128;
    codBil.setModuleWidth(UnitConv.in2mm(1.0f / resou)); //makes the narrow bar 
    //width exactly one pixel
    codBil.setHeight(10);
    codBil.setFontSize(2);
    codBil.setFontName("Helvetica");
    // cod.doQuietZone(true);
    codBil.getBarWidth(2);
    // bean.setVerticalQuietZone(1);
    codBil.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);

    //  File outputFileBillId = new File("C:\\tomcat6\\webapps\\MEDISUN_HEALTH_CARE_V2_Final\\barcode/" + dpsb.getBillId() + ".png"); // Mostofa bhi
    File outputFileBillId = new File(
            request.getSession().getServletContext().getRealPath("/barcode/" + dpsb.getBillId() + ".png"));

    OutputStream outB = new FileOutputStream(outputFileBillId);
    try {
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(outB, "image/x-png", reso,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        codBil.generateBarcode(canvas, dpsb.getBillId().toString());

        canvas.finish();
    } finally {
        outB.close();
    }

    ///// End 
    model.addAttribute("discountAount", dBillColl.getDiscountAmount());

    return "redirect:/module/billing/billprint.htm?patientId=" + patientId;
    //module/billing/directbillingqueue.form

}