Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getInstance.

Prototype

public static final NumberFormat getInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.aol.framework.helper.report.CustomizedReporter.java

synchronized private void generateTestExecutionStatus(boolean emailable, List<ISuite> suites,
        PrintWriter f_out) {// w ww .  j ava2  s  .c  o m
    String testName = "";

    int totalPassedMethods = 0;
    int totalFailedMethods = 0;
    int totalSkippedMethods = 0;
    int totalSkippedConfigurationMethods = 0;
    int totalFailedConfigurationMethods = 0;
    int totalAutomationErrors = 0;
    int totalMethods = 0;

    int suite_totalPassedMethods = 0;
    int suite_totalFailedMethods = 0;
    int suite_totalSkippedMethods = 0;
    int suite_totalAutomationErrors = 0;

    String suite_passPercentage = "";
    String suiteName = "";

    ITestContext overview = null;
    HashMap<String, String> dashboardReportMap = new HashMap<String, String>();

    String dashboardAppGroup = "";

    for (ISuite suite : suites) {
        suiteName = suite.getName();
        TestHelper.logger.info(">> " + suiteName + " <<");
        Map<String, ISuiteResult> tests = suite.getResults();
        NumberFormat nf = NumberFormat.getInstance();

        for (ISuiteResult r : tests.values()) {
            overview = r.getTestContext();
            testName = overview.getName();

            totalPassedMethods = overview.getPassedTests().getAllMethods().size();
            totalFailedMethods = overview.getFailedTests().getAllMethods().size();
            totalAutomationErrors = overview.getFailedButWithinSuccessPercentageTests().getAllMethods().size();
            totalSkippedMethods = overview.getSkippedTests().getAllMethods().size();
            totalFailedConfigurationMethods = overview.getFailedConfigurations().getAllMethods().size(); // this should be 0 as redirected to automation error
            // totalMethods = overview.getAllTestMethods().length;
            totalMethods = totalPassedMethods + totalFailedMethods;

            nf.setMaximumFractionDigits(2);
            nf.setGroupingUsed(true);

            String includedModule = "";
            String includedGroup = "";

            ITestNGMethod[] allTestMethods = overview.getAllTestMethods();
            for (ITestNGMethod testngMethod : allTestMethods) {
                String[] modules = testngMethod.getGroups();
                for (String module : modules) {
                    for (String moduleName : TestHelper.MODULES) {
                        if (module.equalsIgnoreCase(moduleName)) {
                            if (!(includedModule.contains(module))) {
                                includedModule = includedModule + " " + module;
                            }
                        }
                    }
                    for (String groupName : TestHelper.TEST_GROUPS) {
                        if (module.equalsIgnoreCase(groupName)) {
                            if (!(includedGroup.contains(module))) {
                                includedGroup = includedGroup + " " + module;
                            }
                        }
                    }
                }
            }

            String[] nodeInfo = getNodeInfo(overview, testName);

            String browser = nodeInfo[1];
            String browser_version = nodeInfo[2];
            String platform = nodeInfo[0];
            //String nodeIp = nodeInfo[3];

            if (platform == null || platform.trim().length() == 0) {
                platform = "N/A";
            }

            if (browser_version == null || browser_version.trim().length() == 0) {
                browser_version = "N/A";
            }

            if (browser == null || browser.trim().length() == 0) {
                browser = "N/A";
            }

            if (!(dashboardReportMap.containsKey(includedModule))) {
                if (browser_version.equalsIgnoreCase("N/A")) {
                    browser_version = "";
                }
                dashboardReportMap.put(includedModule,
                        "os1~" + platform + "|browser1~" + browser + browser_version + "|testcase_count_1~"
                                + totalMethods + "|pass_count_1~" + totalPassedMethods + "|fail_count_1~"
                                + totalFailedMethods + "|skip_count_1~" + totalSkippedMethods
                                + "|skip_conf_count_1~" + totalSkippedConfigurationMethods
                                + "|fail_conf_count_1~" + totalFailedConfigurationMethods
                                + "|fail_automation_count_1~" + totalAutomationErrors);

            } else {
                for (String key : dashboardReportMap.keySet()) {

                    if (key.equalsIgnoreCase(includedModule)) {
                        if (browser_version.equalsIgnoreCase("N/A")) {
                            browser_version = "";
                        }
                        String value = dashboardReportMap.get(key);
                        int index = StringUtils.countMatches(value, "#") + 1;

                        index += 1;

                        value = value + "#" + "os" + index + "~" + platform + "|browser" + index + "~" + browser
                                + browser_version + "|testcase_count_" + index + "~" + totalMethods
                                + "|pass_count_" + index + "~" + totalPassedMethods + "|fail_count_" + index
                                + "~" + totalFailedMethods + "|skip_count_" + index + "~" + totalSkippedMethods
                                + "|skip_conf_count_" + index + "~" + totalSkippedConfigurationMethods
                                + "|fail_conf_count_" + index + "~" + totalFailedConfigurationMethods
                                + "|fail_automation_count_~" + totalAutomationErrors;
                        dashboardReportMap.put(key, value);
                    }
                }
            }

            dashboardAppGroup = includedGroup;
            suite_totalPassedMethods += totalPassedMethods;
            suite_totalFailedMethods += totalFailedMethods;
            suite_totalAutomationErrors += totalAutomationErrors;
            suite_totalSkippedMethods += totalSkippedMethods;

            suite_passPercentage = getPercentage(nf, suite_totalPassedMethods,
                    suite_totalPassedMethods + suite_totalFailedMethods);

        }

    }

    if (!doneOutputToConsole) {
        //**************************** report to console as status ******************

        int suite_totalTestedMethods = suite_totalPassedMethods + suite_totalFailedMethods;

        System.out.println("[TOTAL_METHODS]: " + (suite_totalTestedMethods));

        System.out.println("[PASSED_METHODS]: " + suite_totalPassedMethods);
        if (suite_totalFailedMethods > 0 || suite_totalPassedMethods == 0)
            System.out.println("[FAILED_METHODS]: " + suite_totalFailedMethods);
        if (suite_totalAutomationErrors > 0)
            System.out.println("[AUTOMATION_ERRORS]: " + suite_totalAutomationErrors);
        if (suite_totalSkippedMethods > 0)
            System.out.println("[SKIPPED_METHODS]: " + suite_totalSkippedMethods);

        System.out.println("[PASSED%]: " + suite_passPercentage);

        TestHelper.setReportProperties(suite_totalTestedMethods, suite_totalPassedMethods,
                suite_totalFailedMethods, suite_totalSkippedMethods, suite_passPercentage,
                suite_totalAutomationErrors);
        //********************************************************************************
    }

    StringBuilder dashboardResults = new StringBuilder();
    if (!emailable) {
        dashboardResults.append(
                "<table id=\"myTable\" width=\"100%\" cellspacing=0 cellpadding=0 class=\"tablesorter\">");
    } else {
        dashboardResults.append("<table " + classParam + " cellspacing=\"0\" cellpadding=\"0\" width=\"91%\">");
    }
    dashboardResults
            // .append("<thead><tr> <th>Test Name</th><th>"
            .append("<thead><tr> <th>Module Name</th><th>" + " # Unique TestCases</th><th>"
                    + " # Combinations</th><th>" + " # Passed</th><th>" + " # Failed</th><th>"
                    + " # Warning</th><th>" + " # Skipped</th><th>" + "# Total</th><th>"
                    + "Success Rate</th> </tr> </thead> <tbody>");

    int total_browser_combinations = 0;
    int total_unique_testcases = 0;

    for (String key : dashboardReportMap.keySet()) {

        String fileName = key.trim() + "-Overall" + "-customized-report.html";
        if (!emailable) {

            try {
                generateModuleOverallTestReport(testName, key, suites, fileName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String value = dashboardReportMap.get(key);
        String[] values = value.split("#");

        int testcase_count = 0; //*******************************************
        int pass_count = 0;
        int fail_count = 0;
        int fail_automation_count = 0;
        int skip_count = 0;
        int skip_conf_count = 0;
        int fail_conf_count = 0;
        String appKey = "TEST_APP";
        String appName = TestHelper.getTestConfig(appKey);

        if (dashboardAppGroup.contains("Smoke") && !appName.equalsIgnoreCase("webmail")) {
            appName = appName + "_" + "Smoke";

        } else if (dashboardAppGroup.contains("Regression")) {
            appName = appName + "_" + "Regression";
        }

        String dashboardModule = key;
        //
        //            if (dashboardModule.contains("Compose"))
        //            {
        //                dashboardModule = dashboardModule.replace("Compose", "ComposeMail");
        //            } else if (dashboardModule.contains("Read"))
        //            {
        //                dashboardModule = dashboardModule.replace("Read", "ReadMail");
        //            }

        // int countMatches = StringUtils.countMatches(value, "#") + 1;

        for (String val : values) {

            String[] tokens = val.split("\\|");
            for (String token : tokens) {
                if (token.contains("testcase_count")) {
                    testcase_count = testcase_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("pass_count")) {
                    pass_count = pass_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("fail_count")) {
                    fail_count = fail_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("fail_automation_count")) {
                    fail_automation_count = fail_automation_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("skip_count")) {
                    skip_count = skip_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("skip_conf_count")) {
                    skip_conf_count = skip_conf_count + Integer.parseInt(token.split("~")[1]);
                }
                if (token.contains("fail_conf_count")) {
                    fail_conf_count = fail_conf_count + Integer.parseInt(token.split("~")[1]);
                }
            }

            testcase_count -= skip_count + skip_conf_count + fail_conf_count;
        }

        NumberFormat nformat = NumberFormat.getInstance();
        nformat.setMaximumFractionDigits(2);
        nformat.setGroupingUsed(true);
        String passPercent = getPercentage(nformat, pass_count, pass_count + fail_count);

        String finalStr = "[";
        String[] val = dashboardReportMap.get(key).split("#");

        int unique_testcase = 0;

        int limit = val.length - 1;
        for (int i = 0; i < val.length; i++) {//TODO - unique_testcase is the max num cases among tests, not the total for the module across tests - Steven
            String testCaseCount = (val[i].split("\\|")[2]).split("~")[1];
            int next = Integer.parseInt(testCaseCount);
            if (next > unique_testcase) {
                unique_testcase = next;
            }
            finalStr = finalStr + testCaseCount + " T * 1 B]";
            if (i != limit) {
                finalStr += " + [";
            }
        }
        //unique_testcase = 
        String finalString = "";
        //            if ((unique_testcase * values.length) != (pass_count + fail_count + skip_count))
        //            {
        //                finalString = "<a href=\"#\" title=\"" + finalStr + "\">" + (pass_count + fail_count + skip_count)
        //                        + "</a>";
        //                
        //            } else
        {
            finalString = String.valueOf((pass_count + fail_count + fail_automation_count + skip_count));
        }

        String passCount = "";
        String failCount = "";
        String automationErrorCount = "";
        String skipCount = "";

        if (pass_count > 0) {
            passCount = "<td bgcolor=\"" + passColor + "\"><font color=\"white\"><b>" + pass_count
                    + "</b></font></td>";
        } else {
            passCount = "<td>" + pass_count + "</td>";
        }

        if (fail_count > 0) {
            failCount = "<td bgcolor=\"" + failColor + "\"><font color=\"white\"><b>" + fail_count
                    + "</b></font></td>";
        } else {
            failCount = "<td>" + fail_count + "</td>";
        }
        if (fail_automation_count > 0) {
            automationErrorCount = "<td bgcolor=\"" + warnColor + "\"><font color=\"white\"><b>"
                    + fail_automation_count + "</b></font></td>";
        } else {
            automationErrorCount = "<td>" + fail_automation_count + "</td>";
        }

        if (skip_count > 0) {
            skipCount = "<td bgcolor=\"" + skipColor + "\"><font color=\"white\"><b>" + skip_count
                    + "</b></font></td>";
        } else {
            skipCount = "<td>" + skip_count + "</td>";
        }
        if (!emailable || !disableCss) {
            dashboardResults.append("<tr><td><b><a href='" + TestHelper.jenkinsBuildUrl
                    + TestHelper.jenkinsCustomReportTitle + TestHelper.customReportDirLink + fileName + "'>"
                    + dashboardModule + "</b></td><td>"
                    // + testName + "</b></td><td>"  
                    + unique_testcase + "</td><td>" + values.length + "</td>" + passCount + failCount
                    + automationErrorCount + skipCount + "<td>" + finalString + "</td><td><font color=\""
                    + passPercentageColor + "\"><b>" + passPercent + " %" + "</b></font></td></tr>");
        } else {
            dashboardResults.append("<tr><td><b>" + dashboardModule + "</b></td><td>"
            //+ testName + "</b></td><td>"  
                    + unique_testcase + "</td><td>" + values.length + "</td><td>" + pass_count + "</td><td>"
                    + fail_count + "</td><td>" + fail_automation_count + "</td><td>" + skip_count + "</td><td>"
                    + finalString + "</td><td><b>" + passPercent + " %" + "</td></tr>");
        }
        if (total_browser_combinations < values.length) {
            total_browser_combinations = values.length;
        }

        total_unique_testcases += unique_testcase;
    }

    dashboardResults.append("</tbody></table>");

    if (!emailable || !disableCss) {
        String suite_pass = "";
        String suite_fail = "";
        String suite_automation_error = "";
        String suite_skip = "";

        if (suite_totalPassedMethods > 0) {
            suite_pass = "<td bgcolor=\"" + passColor + "\"><font color=\"white\"><b>"
                    + suite_totalPassedMethods + "</b></font></td>";
        } else {
            suite_pass = "<td>" + suite_totalPassedMethods + "</td>";
        }

        if (suite_totalFailedMethods > 0) {
            suite_fail = "<td bgcolor=\"" + failColor + "\"><font color=\"white\"><b>"
                    + suite_totalFailedMethods + "</b></font></td>";
        } else {
            suite_fail = "<td>" + suite_totalFailedMethods + "</td>";
        }
        if (suite_totalAutomationErrors > 0) {
            suite_automation_error = "<td bgcolor=\"" + warnColor + "\"><font color=\"white\"><b>"
                    + suite_totalAutomationErrors + "</b></font></td>";
        } else {
            suite_automation_error = "<td>" + suite_totalAutomationErrors + "</td>";
        }
        if (suite_totalSkippedMethods > 0) {
            suite_skip = "<td bgcolor=\"" + skipColor + "\"><font color=\"white\"><b>"
                    + suite_totalSkippedMethods + "</b></font></td>";
        } else {
            suite_skip = "<td>" + suite_totalSkippedMethods + "</td>";
        }

        // Summary Table
        f_out.println("<p><b>Overall Execution Summary</b></p>");

        if (!emailable) {
            f_out.println("<table class=\"tablesorter\" width=\"100%\">");
        } else {
            f_out.println("<table " + classParam + "  cellspacing=\"0\" cellpadding=\"0\" width=\"91%\">");
        }
        f_out.println(//"<table class=\"param\" width=\"100%\">"+
                "<thead><tr><th>Test Suite Name</th><th>" + "# Unique TestCases</th><th>"
                        + "# Combinations</th> <th>" + "# Passed</th> <th>" + "# Failed</th> <th>"
                        + "# Warning</th> <th>" + "# Skipped</th><th>" + "# Total</th> <th>"
                        + "Success Rate</th> </tr> </thead>" + " <tbody> <tr><td><b>" + suiteName
                        + "</b></td><td>" + total_unique_testcases + "</td><td>" + total_browser_combinations
                        + "</td>" + suite_pass + suite_fail + suite_automation_error + suite_skip + "<td>"
                        + (suite_totalPassedMethods + suite_totalFailedMethods + suite_totalSkippedMethods
                                + suite_totalAutomationErrors)
                        + "</td><td><font color=\"" + passPercentageColor + "\"><b>" + suite_passPercentage
                        + " %" + "</b></font></td></tr></tbody></table>");
    } else {
        f_out.println("<b><font color=\"" + titleColor + "\">Overall Execution Summary</font></b><br/><br/>");
        f_out.println("<table " + classParam + "  cellspacing=\"0\" cellpadding=\"0\" width=\"91%\">"
                + "<thead><tr><th>Test Suite Name</th><th>" + "# Unique TestCases</th><th>"
                + "# Combinations</th> <th>" + "# Passed</th> <th>" + "# Failed</th> <th>"
                + "# Warning</th> <th>" + "# Skipped</th><th>" + "# Total</th> <th>"
                + "Success Rate</th> </tr> </thead>" + " <tbody> <tr><td><b>" + suiteName + "</b></td><td>"
                + total_unique_testcases + "</td><td>" + total_browser_combinations + "</td><td>"
                + suite_totalPassedMethods + "</td><td>" + suite_totalFailedMethods + "</td><td>"
                + suite_totalAutomationErrors + "</td><td>" + suite_totalSkippedMethods + "</td><td>"
                + (suite_totalPassedMethods + suite_totalFailedMethods + suite_totalSkippedMethods
                        + suite_totalAutomationErrors)
                + "</td><td>" + suite_passPercentage + " %" + "</td></tr></tbody></table>");

    }
    f_out.flush();

    f_out.println("<br/>");
    f_out.println("<p><b>Modulewise Execution Summary</b></p>");
    f_out.println(dashboardResults);
    //        if(!emailable){
    //        f_out.println("<br/><h4>Legend:</h4>");
    //        f_out.print("<ul>");
    //        f_out.println("<li>T: Unique Testcase</li>");
    //        f_out.println("<li>B: Unique Browser Combination</li>");
    //        f_out.print("</ul>");
    //        }else{
    f_out.println("<br/><br/><br/><br/>");
    //        }
    f_out.flush();
}

From source file:uk.ac.gda.dls.client.views.ReadonlyScannableComposite.java

private void setVal(String newVal) {
    if (decimalPlaces != null) {
        Scanner sc = new Scanner(newVal.trim());
        if (sc.hasNextDouble()) {
            NumberFormat format = NumberFormat.getInstance();
            format.setMaximumFractionDigits(decimalPlaces.intValue());
            newVal = format.format(sc.nextDouble());
        }/*from  w  ww .j ava 2s .co  m*/
        sc.close();
    }
    val = newVal;
    if (!isDisposed()) {
        if (minPeriodMS != null) {
            if (!textUpdateScheduled) {
                textUpdateScheduled = true;
                display.asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        display.timerExec(minPeriodMS, setTextRunnable);
                    }
                });
            }
        } else {
            display.asyncExec(setTextRunnable);
        }
    }
}

From source file:canreg.client.analysis.Tools.java

public static JFreeChart generateJChart(Collection<CancerCasesCount> casesCounts, String fileName,
        String header, FileTypes fileType, ChartType chartType, boolean includeOther, boolean legendOn,
        Double restCount, Double allCount, Color color, String labelsCategoryName) {
    JFreeChart chart;//from  w  w  w.j a v  a  2s .  c  o m
    if (chartType == ChartType.PIE) {
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(1);
        DefaultPieDataset dataset = new DefaultKeyedValuesDataset();
        int position = 0;
        for (CancerCasesCount count : casesCounts) {
            dataset.insertValue(position++,
                    count.toString() + " (" + format.format(count.getCount() / allCount * 100) + "%)",
                    count.getCount());
        }
        if (includeOther) {
            dataset.insertValue(position++,
                    "Other: " + restCount.intValue() + " (" + format.format(restCount / allCount * 100) + "%)",
                    restCount);
        }
        chart = ChartFactory.createPieChart(header, dataset, legendOn, false, Locale.getDefault());
        Tools.setPiePlotColours(chart, casesCounts.size() + 1, color.brighter());

    } else { // assume barchart
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        for (CancerCasesCount count : casesCounts) {
            dataset.addValue(count.getCount(), count.getLabel(), count.toString());
        }
        if (includeOther) {
            dataset.addValue(restCount.intValue(), "Other", "Other: " + restCount);
        }
        chart = ChartFactory.createStackedBarChart(header, labelsCategoryName, "Cases", dataset,
                PlotOrientation.HORIZONTAL, legendOn, true, false);

        Tools.setBarPlotColours(chart, casesCounts.size() + 1, color.brighter());
    }
    return chart;
}

From source file:com.anrisoftware.globalpom.format.latlong.LatitudeFormat.java

private double parseDecimal(String latitude) throws ParseException {
    return ((Number) NumberFormat.getInstance().parseObject(latitude)).doubleValue();
}

From source file:assign3.client.WaypointClient.java

public void actionPerformed(ActionEvent e) {
    try {/*from  w  w w  .  jav a 2s .  com*/
        if (e.getActionCommand().equals("Remove")) {
            debug("you clicked Remove Waypoint");
            frWps.removeItem(frWps.getSelectedItem());
            toWps.removeItem(toWps.getSelectedItem());
        } else if (e.getActionCommand().equals("Add")) {
            debug("you clicked Add Waypoint");
            addWaypoint();
            distBearIn.setText("Added: " + nameIn.getText());
        } else if (e.getActionCommand().equals("Modify")) {
            debug("you clicked Modify Waypoint");
        } else if (e.getActionCommand().equals("GetLatLon")) {
            debug("you clicked Get Lat/Lon");
        } else if (e.getActionCommand().equals("exportToJSON")) {
            debug("you clicked export to JSON");
            String[] names = server.getNames(); //Check this
            JSONObject obj = new JSONObject();
            for (int i = 0; i < names.length; i++) {
                Waypoint wp = server.get(names[i]);
                obj.put(names[i], wp.toJson());
            }
        } else if (e.getActionCommand().equals("Distance")) {
            debug("you clicked Distance and Bearing");
            String wpFrom = frWps.getSelectedItem().toString();
            String wpTo = toWps.getSelectedItem().toString();
            NumberFormat nf = NumberFormat.getInstance();
            nf.setMaximumFractionDigits(4);
            String distCalc = nf.format(server.distGC(wpFrom, wpTo));
            String dirCalc = nf.format(server.directionGC(wpFrom, wpTo));
            server.distGC(frWps.getName(), toWps.getName());
            server.directionGC(frWps.getName(), toWps.getName());
            distBearIn.setText("Distance from " + wpFrom + " to " + wpTo + " is " + distCalc
                    + " miles, bearing " + dirCalc + ".");
        }
    } catch (RemoteException ex) {
        System.out.println("Server connection error.");
    } catch (Exception e1) {
        e1.printStackTrace();
    }
}

From source file:org.sakaiproject.gradebookng.tool.panels.AssignmentStatisticsPanel.java

@Override
public void onInitialize() {
    super.onInitialize();

    final Long assignmentId = ((Model<Long>) getDefaultModel()).getObject();

    final Assignment assignment = this.businessService.getAssignment(assignmentId.longValue());

    AssignmentStatisticsPanel.this.window.setTitle(
            (new StringResourceModel("label.statistics.title", null, new Object[] { assignment.getName() })
                    .getString()));/*from ww  w.  ja  v  a 2 s  .  c  om*/

    final List<GbStudentGradeInfo> gradeInfo = this.businessService.buildGradeMatrix(Arrays.asList(assignment));

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

    for (int i = 0; i < gradeInfo.size(); i++) {
        final GbStudentGradeInfo studentGradeInfo = gradeInfo.get(i);

        final Map<Long, GbGradeInfo> studentGrades = studentGradeInfo.getGrades();
        final GbGradeInfo grade = studentGrades.get(assignmentId);

        if (grade == null || grade.getGrade() == null) {
            // this is not the grade you are looking for
        } else {
            allGrades.add(Double.valueOf(grade.getGrade()));
        }
    }

    Collections.sort(allGrades);

    final DefaultCategoryDataset data = new DefaultCategoryDataset();

    final Map<String, Integer> counts = new TreeMap<>();
    Integer extraCredits = 0;

    // Start off with a 0-50% range
    counts.put(String.format("%d-%d", 0, 50), 0);

    final int range = 10;
    for (int start = 50; start < 100; start = start + range) {
        final String key = String.format("%d-%d", start, start + range);
        counts.put(key, 0);
    }

    for (final Double grade : allGrades) {
        if (isExtraCredit(grade, assignment)) {
            extraCredits = extraCredits + 1;
            continue;
        }

        final double percentage;
        if (GradingType.PERCENTAGE.equals(this.gradingType)) {
            percentage = grade;
        } else {
            percentage = grade / assignment.getPoints() * 100;
        }

        final int total = Double.valueOf(Math.ceil(percentage) / range).intValue();

        int start = total * range;

        if (start == 100) {
            start = start - range;
        }

        String key = String.format("%d-%d", start, start + range);

        if (start < 50) {
            key = String.format("%d-%d", 0, 50);
        }

        counts.put(key, counts.get(key) + 1);
    }

    for (final String label : counts.keySet()) {
        data.addValue(counts.get(label), "count", label);
    }
    if (extraCredits > 0) {
        data.addValue(extraCredits, "count", getString("label.statistics.chart.extracredit"));
    }

    final JFreeChart chart = ChartFactory.createBarChart(null, // the chart title
            getString("label.statistics.chart.xaxis"), // the label for the category axis
            getString("label.statistics.chart.yaxis"), // the label for the value axis
            data, // the dataset for the chart
            PlotOrientation.VERTICAL, // the plot orientation
            false, // show legend
            true, // show tooltips
            false); // show urls

    chart.setBorderVisible(false);

    chart.setAntiAlias(false);

    final CategoryPlot categoryPlot = chart.getCategoryPlot();
    final BarRenderer br = (BarRenderer) categoryPlot.getRenderer();

    br.setItemMargin(0);
    br.setMinimumBarLength(0.05);
    br.setMaximumBarWidth(0.1);
    br.setSeriesPaint(0, new Color(51, 122, 183));
    br.setBarPainter(new StandardBarPainter());
    br.setShadowPaint(new Color(220, 220, 220));
    BarRenderer.setDefaultShadowsVisible(true);

    br.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator(getString("label.statistics.chart.tooltip"),
            NumberFormat.getInstance()));

    categoryPlot.setRenderer(br);

    // show only integers in the count axis
    categoryPlot.getRangeAxis().setStandardTickUnits(new NumberTickUnitSource(true));
    categoryPlot.setBackgroundPaint(Color.white);

    add(new JFreeChartImageWithToolTip("chart", Model.of(chart), "tooltip", 540, 300));

    add(new Label("graded", String.valueOf(allGrades.size())));

    if (allGrades.size() > 0) {
        add(new Label("average", constructAverageLabel(allGrades, assignment)));
        add(new Label("median", constructMedianLabel(allGrades, assignment)));
        add(new Label("lowest", constructLowestLabel(allGrades, assignment)));
        add(new Label("highest", constructHighestLabel(allGrades, assignment)));
        add(new Label("deviation", constructStandardDeviationLabel(allGrades)));
    } else {
        add(new Label("average", "-"));
        add(new Label("median", "-"));
        add(new Label("lowest", "-"));
        add(new Label("highest", "-"));
        add(new Label("deviation", "-"));
    }

    add(new GbAjaxLink("done") {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(final AjaxRequestTarget target) {
            AssignmentStatisticsPanel.this.window.close(target);
        }
    });
}

From source file:com.alibaba.druid.benckmark.pool.CaseKylin_mysql.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from w  ww.j av  a 2 s  .  com

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        PreparedStatement stmt = conn.prepareStatement("SELECT 1 FROM DUAL");
                        ResultSet rs = stmt.executeQuery();
                        rs.next();
                        rs.getInt(1);
                        rs.close();
                        stmt.close();
                        conn.close();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.autentia.intra.bean.admin.ProjectBean.java

public String getSiguienteRefLab() {
    if (project.getClient() != null
            && (project.getReferenciaLaboratorio() == null || project.getReferenciaLaboratorio().equals(""))) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(2);/*  ww  w  .ja v a  2 s.com*/
        nf.setGroupingUsed(false);
        String anio = nf.format(new Date().getYear() - 100);

        ProjectSearch ps = new ProjectSearch();
        String acronimo = project.getClient().getAcronimo();
        ps.setReferenciaLaboratorio(acronimo + "%/" + anio + "%");
        List<Project> todos = manager.getAllEntities(ps, new SortCriteria("id", false));
        nf.setMinimumIntegerDigits(4);
        int t = 0;
        if (todos.size() >= 0) {
            try {
                String x = todos.get(0).getReferenciaLaboratorio();
                x = x.replaceFirst(acronimo, "");
                t = Integer.parseInt(x.substring(0, x.indexOf('/')));
            } catch (Exception ex) {
            }
        }
        return acronimo + nf.format(t + 1) + "/" + anio;
    } else {
        return project.getReferenciaLaboratorio();
    }
}

From source file:com.alibaba.druid.benckmark.pool.Case2.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    final AtomicLong blockedStat = new AtomicLong();
    final AtomicLong waitedStat = new AtomicLong();

    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();//from  w w w .  j ava  2  s  .  c o  m

                    long threadId = Thread.currentThread().getId();

                    long startBlockedCount, startWaitedCount;
                    {
                        ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId);
                        startBlockedCount = threadInfo.getBlockedCount();
                        startWaitedCount = threadInfo.getWaitedCount();
                    }
                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();
                        conn.close();
                    }

                    ThreadInfo threadInfo = ManagementFactory.getThreadMXBean().getThreadInfo(threadId);
                    long blockedCount = threadInfo.getBlockedCount() - startBlockedCount;
                    long waitedCount = threadInfo.getWaitedCount() - startWaitedCount;

                    blockedStat.addAndGet(blockedCount);
                    waitedStat.addAndGet(waitedCount);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC + " blockedCount "
            + blockedStat.get() + " waitedCount " + waitedStat.get());
}

From source file:au.org.theark.lims.web.component.biospecimen.batchaliquot.form.BatchAliquotBiospecimenForm.java

public void initialiseForm() {
    numberToCreateTxtFld = new TextField<Number>("numberToCreate",
            new PropertyModel(getModelObject(), "numberToCreate")) {
        /**//from ww w.  ja v  a 2s.  c  o m
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public boolean isVisible() {
            // Only visible on first instantation of form, once entered and saved, hidden by enclosure
            return getModelObject() == null;
        }
    };

    add(numberToCreateTxtFld);
    add(new AjaxButton("numberToCreateButton") {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (numberToCreateTxtFld.getDefaultModelObject() != null) {
                int numberToCreate = ((Integer) numberToCreateTxtFld.getDefaultModelObject());
                for (int i = 0; i < numberToCreate; i++) {
                    Biospecimen biospecimen = new Biospecimen();
                    listEditor.addItem(biospecimen);
                    listEditor.updateModel();
                    target.add(form);
                }
            } else {
                error("Please enter a valid number.");
                onError(target, form);
            }
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
        }
    });

    add(buildListEditor());

    add(new Label("parentBiospecimen.biospecimenUid",
            new PropertyModel(getModelObject(), "parentBiospecimen.biospecimenUid")));
    parentQtyLbl = new Label("parentBiospecimen.quantity",
            new PropertyModel(getModelObject(), "parentBiospecimen.quantity")) {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public <C> IConverter<C> getConverter(Class<C> type) {
            DoubleConverter doubleConverter = new DoubleConverter();
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMinimumFractionDigits(1);
            doubleConverter.setNumberFormat(getLocale(), numberFormat);
            return (IConverter<C>) doubleConverter;
        }
    };
    add(parentQtyLbl);
    add(new Label("parentBiospecimen.unit.name",
            new PropertyModel(getModelObject(), "parentBiospecimen.unit.name")));

    add(new AjaxEditorButton(Constants.NEW) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
        }

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            Biospecimen biospecimen = new Biospecimen();
            copyBiospecimen = false;
            listEditor.addItem(biospecimen);
            target.add(form);
        }
    }.setDefaultFormProcessing(false));

    add(new AjaxButton(Constants.SAVE) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            onSave(target);
            target.add(feedbackPanel);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
        }

        @Override
        public boolean isVisible() {
            return false;
        }
    });

    add(new AjaxButton(Constants.SAVEANDCLOSE) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            if (onSave(target)) {
                modalWindow.close(target);
            }
            target.add(feedbackPanel);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
        }
    });

    add(new AjaxButton(Constants.CANCEL) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            modalWindow.close(target);
        }

        @Override
        protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.add(feedbackPanel);
        }
    }.setDefaultFormProcessing(false));
}