Example usage for java.text NumberFormat setGroupingUsed

List of usage examples for java.text NumberFormat setGroupingUsed

Introduction

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

Prototype

public void setGroupingUsed(boolean newValue) 

Source Link

Document

Set whether or not grouping will be used in this format.

Usage

From source file:com.ibm.bi.dml.test.utils.TestUtils.java

/**
 * <p>/* w  ww  .ja  v a2 s .c om*/
 * Returns the string representation of a double value which can be used in
 * a DML script.
 * </p>
 * 
 * @param value
 *            double value
 * @return string representation
 */
public static String getStringRepresentationForDouble(double value) {
    NumberFormat nf = DecimalFormat.getInstance(new Locale("EN"));
    nf.setGroupingUsed(false);
    nf.setMinimumFractionDigits(1);
    nf.setMaximumFractionDigits(20);
    return nf.format(value);
}

From source file:org.apache.tajo.storage.FileTablespace.java

/**
 * Finalizes result data. Tajo stores result data in the staging directory.
 * If the query fails, clean up the staging directory.
 * Otherwise the query is successful, move to the final directory from the staging directory.
 *
 * @param queryContext The query property
 * @param changeFileSeq If true change result file name with max sequence.
 * @return Saved path/*from  w  w  w  . j av a  2 s .c om*/
 * @throws java.io.IOException
 */
protected Path commitOutputData(OverridableConf queryContext, boolean changeFileSeq) throws IOException {
    Path stagingDir = new Path(queryContext.get(QueryVars.STAGING_DIR));
    Path stagingResultDir = new Path(stagingDir, TajoConstants.RESULT_DIR_NAME);
    Path finalOutputDir;
    if (!queryContext.get(QueryVars.OUTPUT_TABLE_URI, "").isEmpty()) {
        finalOutputDir = new Path(queryContext.get(QueryVars.OUTPUT_TABLE_URI));
        try {
            FileSystem fs = stagingResultDir.getFileSystem(conf);

            if (queryContext.getBool(QueryVars.OUTPUT_OVERWRITE, false)) { // INSERT OVERWRITE INTO

                // It moves the original table into the temporary location.
                // Then it moves the new result table into the original table location.
                // Upon failed, it recovers the original table if possible.
                boolean movedToOldTable = false;
                boolean committed = false;
                Path oldTableDir = new Path(stagingDir, TajoConstants.INSERT_OVERWIRTE_OLD_TABLE_NAME);
                ContentSummary summary = fs.getContentSummary(stagingResultDir);

                // When inserting empty data into a partitioned table, check if keep existing data need to be remove or not.
                boolean overwriteEnabled = queryContext
                        .getBool(SessionVars.PARTITION_NO_RESULT_OVERWRITE_ENABLED);

                // If existing data doesn't need to keep, check if there are some files.
                if ((!queryContext.get(QueryVars.OUTPUT_PARTITIONS, "").isEmpty())
                        && (!overwriteEnabled || (overwriteEnabled && summary.getFileCount() > 0L))) {
                    // This is a map for existing non-leaf directory to rename. A key is current directory and a value is
                    // renaming directory.
                    Map<Path, Path> renameDirs = new HashMap<>();
                    // This is a map for recovering existing partition directory. A key is current directory and a value is
                    // temporary directory to back up.
                    Map<Path, Path> recoveryDirs = new HashMap<>();

                    try {
                        if (!fs.exists(finalOutputDir)) {
                            fs.mkdirs(finalOutputDir);
                        }

                        visitPartitionedDirectory(fs, stagingResultDir, finalOutputDir,
                                stagingResultDir.toString(), renameDirs, oldTableDir);

                        // Rename target partition directories
                        for (Map.Entry<Path, Path> entry : renameDirs.entrySet()) {
                            // Backup existing data files for recovering
                            if (fs.exists(entry.getValue())) {
                                String recoveryPathString = entry.getValue().toString()
                                        .replaceAll(finalOutputDir.toString(), oldTableDir.toString());
                                Path recoveryPath = new Path(recoveryPathString);
                                fs.rename(entry.getValue(), recoveryPath);
                                fs.exists(recoveryPath);
                                recoveryDirs.put(entry.getValue(), recoveryPath);
                            }
                            // Delete existing directory
                            fs.delete(entry.getValue(), true);
                            // Rename staging directory to final output directory
                            fs.rename(entry.getKey(), entry.getValue());
                        }

                    } catch (IOException ioe) {
                        // Remove created dirs
                        for (Map.Entry<Path, Path> entry : renameDirs.entrySet()) {
                            fs.delete(entry.getValue(), true);
                        }

                        // Recovery renamed dirs
                        for (Map.Entry<Path, Path> entry : recoveryDirs.entrySet()) {
                            fs.delete(entry.getValue(), true);
                            fs.rename(entry.getValue(), entry.getKey());
                        }

                        throw new IOException(ioe.getMessage());
                    }
                } else { // no partition
                    try {

                        // if the final output dir exists, move all contents to the temporary table dir.
                        // Otherwise, just make the final output dir. As a result, the final output dir will be empty.
                        if (fs.exists(finalOutputDir)) {
                            fs.mkdirs(oldTableDir);

                            for (FileStatus status : fs.listStatus(finalOutputDir, hiddenFileFilter)) {
                                fs.rename(status.getPath(), oldTableDir);
                            }

                            movedToOldTable = fs.exists(oldTableDir);
                        } else { // if the parent does not exist, make its parent directory.
                            fs.mkdirs(finalOutputDir);
                        }

                        // Move the results to the final output dir.
                        for (FileStatus status : fs.listStatus(stagingResultDir)) {
                            fs.rename(status.getPath(), finalOutputDir);
                        }

                        // Check the final output dir
                        committed = fs.exists(finalOutputDir);

                    } catch (IOException ioe) {
                        // recover the old table
                        if (movedToOldTable && !committed) {

                            // if commit is failed, recover the old data
                            for (FileStatus status : fs.listStatus(finalOutputDir, hiddenFileFilter)) {
                                fs.delete(status.getPath(), true);
                            }

                            for (FileStatus status : fs.listStatus(oldTableDir)) {
                                fs.rename(status.getPath(), finalOutputDir);
                            }
                        }

                        throw new IOException(ioe.getMessage());
                    }
                }
            } else {
                String queryType = queryContext.get(QueryVars.COMMAND_TYPE);

                if (queryType != null && queryType.equals(NodeType.INSERT.name())) { // INSERT INTO an existing table

                    NumberFormat fmt = NumberFormat.getInstance();
                    fmt.setGroupingUsed(false);
                    fmt.setMinimumIntegerDigits(3);

                    if (!queryContext.get(QueryVars.OUTPUT_PARTITIONS, "").isEmpty()) {
                        for (FileStatus eachFile : fs.listStatus(stagingResultDir)) {
                            if (eachFile.isFile()) {
                                LOG.warn("Partition table can't have file in a staging dir: "
                                        + eachFile.getPath());
                                continue;
                            }
                            moveResultFromStageToFinal(fs, stagingResultDir, eachFile, finalOutputDir, fmt, -1,
                                    changeFileSeq);
                        }
                    } else {
                        int maxSeq = StorageUtil.getMaxFileSequence(fs, finalOutputDir, false) + 1;
                        for (FileStatus eachFile : fs.listStatus(stagingResultDir)) {
                            if (eachFile.getPath().getName().startsWith("_")) {
                                continue;
                            }
                            moveResultFromStageToFinal(fs, stagingResultDir, eachFile, finalOutputDir, fmt,
                                    maxSeq++, changeFileSeq);
                        }
                    }
                    // checking all file moved and remove empty dir
                    verifyAllFileMoved(fs, stagingResultDir);
                    FileStatus[] files = fs.listStatus(stagingResultDir);
                    if (files != null && files.length != 0) {
                        for (FileStatus eachFile : files) {
                            LOG.error("There are some unmoved files in staging dir:" + eachFile.getPath());
                        }
                    }
                } else { // CREATE TABLE AS SELECT (CTAS)
                    if (fs.exists(finalOutputDir)) {
                        for (FileStatus status : fs.listStatus(stagingResultDir)) {
                            fs.rename(status.getPath(), finalOutputDir);
                        }
                    } else {
                        fs.rename(stagingResultDir, finalOutputDir);
                    }
                    LOG.info("Moved from the staging dir to the output directory '" + finalOutputDir);
                }
            }

            // remove the staging directory if the final output dir is given.
            Path stagingDirRoot = stagingDir.getParent();
            fs.delete(stagingDirRoot, true);
        } catch (Throwable t) {
            LOG.error(t);
            throw new IOException(t);
        }
    } else {
        finalOutputDir = new Path(stagingDir, TajoConstants.RESULT_DIR_NAME);
    }

    return finalOutputDir;
}

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);/*from w  ww .  j a v a2 s . c  om*/
        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:io.hummer.util.test.GenericTestResult.java

public String getPlottableAverages3D(List<Integer> levels, String[] keyTemplates, ResultType type,
        String... additionalCommands) {
    StringBuilder b = new StringBuilder();
    NumberFormat f = NumberFormat.getInstance(Locale.US);
    f.setMinimumFractionDigits(3);//from   ww  w  . j  a  v  a2  s.co  m
    f.setMaximumFractionDigits(3);
    f.setGroupingUsed(false);
    for (int l : levels) {
        for (String t : keyTemplates) {
            String key = t.replaceAll("<level>", "" + l);
            Double val = 0.0;
            if (type == ResultType.THROUGHPUT)
                val = getThroughput(key);
            else if (type == ResultType.MEAN)
                val = getMean(key);
            if (val.isNaN())
                val = 0.0;
            b.append(f.format(val));
            b.append("\n");
        }
        b.append("\n");
    }
    return b.toString();
}

From source file:fr.hoteia.qalingo.core.web.util.impl.RequestUtilImpl.java

/**
 *
 *//*from   w w  w.  j ava 2s  .  c  om*/
public NumberFormat getNumberFormat(final RequestData requestData, final String currencyCode,
        final RoundingMode roundingMode, final int maximumFractionDigits, final int minimumFractionDigits,
        final int maximumIntegerDigits, final int minimumIntegerDigits) throws Exception {
    final Localization localization = requestData.getLocalization();
    final Locale locale = localization.getLocale();
    NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
    formatter.setGroupingUsed(true);
    formatter.setParseIntegerOnly(false);
    formatter.setRoundingMode(roundingMode);
    Currency currency = Currency.getInstance(currencyCode);
    formatter.setCurrency(currency);

    formatter.setMaximumFractionDigits(maximumFractionDigits);
    formatter.setMinimumFractionDigits(minimumFractionDigits);

    formatter.setMaximumIntegerDigits(maximumIntegerDigits);
    formatter.setMinimumIntegerDigits(minimumIntegerDigits);

    return formatter;
}

From source file:io.hummer.util.test.GenericTestResult.java

public String getPlottableAverages(List<?> levels, String[] xValueNames, String indexColumn, ResultType type,
        String... additionalCommands) {
    StringBuilder b = new StringBuilder();
    NumberFormat f = NumberFormat.getInstance(Locale.US);
    f.setMinimumFractionDigits(3);//from w  w w . j a  va 2 s.  com
    f.setMaximumFractionDigits(3);
    f.setGroupingUsed(false);

    List<String> commandsList = Arrays.asList(additionalCommands);

    for (int i = 0; i < levels.size(); i++) {
        String index = "" + levels.get(i);
        if (indexColumn != null) {
            index = "" + getMean(indexColumn.replaceAll("<level>", "" + levels.get(i)));
        }

        int modulo = commandsList.contains(CMD_ONLY_EVERY_2ND_XTICS) ? 2
                : commandsList.contains(CMD_ONLY_EVERY_3RD_XTICS) ? 3 : 1;
        if (i % modulo == 0) {
            b.append(index);
        } else {
            b.append("_");
        }

        for (int j = 0; j < xValueNames.length; j++) {
            b.append("\t");
            String nameString = xValueNames[j];
            nameString = nameString.replaceAll("<level>", "" + levels.get(i));
            if (nameString.equals(xValueNames[j]))
                nameString = nameString + levels.get(i);

            String[] actualNames = nameString.split(":");
            for (String name : actualNames) {

                Double theValue = 0.0;
                if (name.endsWith(".min")) {

                    theValue = getMinimum(name.substring(0, name.length() - ".min".length()));

                } else if (name.endsWith(".max")) {

                    theValue = getMaximum(name.substring(0, name.length() - ".max".length()));

                } else {
                    List<Double> values = getValues(name);
                    if (type == ResultType.MEAN) {
                        Number mean = getMean(values);
                        theValue = mean.doubleValue();
                    } else if (type == ResultType.THROUGHPUT) {
                        theValue = getThroughput(name);
                    }
                    if (values.size() <= 0) {
                        theValue = Double.NaN;
                    }
                }
                if (theValue > 1000000) {
                    b.append(theValue.longValue());
                } else {
                    String val = f.format(theValue);
                    if ((theValue).isNaN()) {
                        //val = "0";
                        val = "NaN";
                    }
                    while (val.length() < 10)
                        val = " " + val;
                    b.append(val);
                }

            }

        }
        b.append("\n");
    }
    return b.toString();
}

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

synchronized private void generateModuleWiseTestReport(String testName, List<ISuite> suites, String newFileName,
        String passedModule, String nodeIp) throws IOException {
    final PrintWriter pw = TestHelper.createFileWriter(TestHelper.customReportDir + newFileName);

    startHtmlPage(pw);// ww w . j av  a2  s . c o m

    pw.println("<button class=\"sexybutton sexysimple sexylarge sexyblack\" onClick=\"location.href='"
            + passedModule + "-Overall-customized-report.html"
            + "'\"><span class=\"prev\">Back to Modulewise Test Execution Summary</span></button>");

    pw.println(
            "<br/><br/><br/><fieldset><legend><b>Modulewise Execution Details</b></legend><br/><table class=\"details\" cellspacing=0 cellpadding=0><tr><td><b>Test Name: </b></td><td>"
                    + testName + "</td></tr>");

    pw.println("<tr><td><b>Node IP: </b></td><td>" + nodeIp + "</td></tr></table></fieldset><br/><br/>");
    pw.println("<table id=\"myTable\" width=\"100%\" cellspacing=0 cellpadding=0 class=\"tablesorter\">");
    pw.println("<thead><tr><th>Module Name</th><th># Passed</th>" + "<th># Failed</th><th># Warning</th>"
            + "<th># Skipped</th><th># Total</th><th>Success Rate</th></tr></thead>");

    HashMap<String, ArrayList<ITestNGMethod>> moduleMap = new HashMap<String, ArrayList<ITestNGMethod>>();

    ITestContext overview = null;

    for (ISuite suite : suites) {
        Map<String, ISuiteResult> tests = suite.getResults();
        for (ISuiteResult r : tests.values()) {
            overview = r.getTestContext();
            if ((overview.getName()).equalsIgnoreCase(testName)) {
                ITestNGMethod[] testngMethods = overview.getAllTestMethods();

                ArrayList<HashMap<String, ITestNGMethod>> moduleMethods = new ArrayList<HashMap<String, ITestNGMethod>>();

                for (ITestNGMethod testngMethod : testngMethods) {
                    String[] groups = testngMethod.getGroups();
                    for (String group : groups) {
                        for (String module : TestHelper.MODULES) {
                            if (group.equalsIgnoreCase(module)) {
                                HashMap<String, ITestNGMethod> tempMap = new HashMap<String, ITestNGMethod>();
                                tempMap.put(module, testngMethod);
                                moduleMethods.add(tempMap);
                            }
                        }
                    }
                }

                for (String module : TestHelper.MODULES) {
                    ArrayList<ITestNGMethod> moduleTestMethods = new ArrayList<ITestNGMethod>();

                    Iterator<HashMap<String, ITestNGMethod>> it = moduleMethods.iterator();

                    while (it.hasNext()) {
                        String moduleName = "";
                        ITestNGMethod testMethod = null;

                        HashMap<String, ITestNGMethod> moduleWithTestMethod = it.next();
                        if (moduleWithTestMethod.containsKey(module)) {
                            moduleName = module;
                            testMethod = moduleWithTestMethod.get(module);
                        }

                        if (module.equalsIgnoreCase(moduleName)) {
                            moduleTestMethods.add(testMethod);
                        }
                    }

                    moduleMap.put(module, moduleTestMethods);
                }
            }
        }
    }

    Set<String> keySet = moduleMap.keySet();
    Iterator<String> it = keySet.iterator();

    for (ISuite suite : suites) {
        Map<String, ISuiteResult> tests = suite.getResults();
        for (ISuiteResult r : tests.values()) {
            overview = r.getTestContext();
            if ((overview.getName()).equalsIgnoreCase(testName)) {
                while (it.hasNext()) {
                    String moduleName = it.next();

                    int totalPassedMethods = 0;
                    int totalFailedMethods = 0;
                    int totalAutomationErrors = 0;
                    int totalSkippedMethods = 0;
                    int totalSkippedConfigurations = 0;
                    int totalFailedConfigurations = 0;

                    ArrayList<ITestNGMethod> values = moduleMap.get(moduleName);
                    ListIterator<ITestNGMethod> it2 = values.listIterator();

                    while (it2.hasNext()) {
                        ITestNGMethod method = it2.next();

                        int failedMethods = overview.getFailedTests().getResults(method).size();
                        int failedAutomationErrors = overview.getFailedButWithinSuccessPercentageTests()
                                .getResults(method).size();
                        int passedMethods = overview.getPassedTests().getResults(method).size();
                        int skippedMethods = overview.getSkippedTests().getResults(method).size();
                        int failedConfiguration = overview.getFailedConfigurations().getResults(method).size();
                        int skippedConfiguration = overview.getSkippedConfigurations().getResults(method)
                                .size();

                        totalPassedMethods += passedMethods;
                        totalFailedMethods += failedMethods;
                        totalAutomationErrors += failedAutomationErrors;
                        totalSkippedMethods += skippedMethods;
                        totalFailedConfigurations += failedConfiguration;
                        totalSkippedConfigurations += skippedConfiguration;

                    }

                    if (values.size() > 0) {
                        String fileName = testName + "-" + moduleName + "-customized-report.html";
                        try {
                            generateModuleTestMethodSummary(testName, moduleName, suites, fileName, values,
                                    nodeIp);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        int totalMethods = totalPassedMethods + totalFailedMethods + totalAutomationErrors
                                + totalSkippedMethods;

                        NumberFormat nf = NumberFormat.getInstance();
                        nf.setMaximumFractionDigits(2);
                        nf.setGroupingUsed(false);

                        String passPercentage = getPercentage(nf, totalPassedMethods, totalMethods);

                        generateModulesRow(pw, fileName, moduleName, totalPassedMethods, totalFailedMethods,
                                totalAutomationErrors, totalSkippedMethods, totalSkippedConfigurations,
                                totalFailedConfigurations, totalMethods, passPercentage);
                    }
                }
                break;
            }
        }
    }

    pw.println("</table>");
    endHtmlPage(pw);
    pw.flush();
    pw.close();
}

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

synchronized private void generateModuleOverallTestReport(String testName, String moduleVar,
        List<ISuite> suites, String newFileName) throws Exception {
    StringBuilder moduleResults = new StringBuilder();

    final PrintWriter pw = TestHelper.createFileWriter(TestHelper.customReportDir + newFileName);

    startHtmlPage(pw);//ww  w  . jav a 2 s .  co m

    pw.println("<button class=\"sexybutton sexysimple sexylarge sexyblack\" onClick=\"location.href='"
            + TestHelper.customizedReportFileLink//customized-test-run-report.html+
            + "'\"><span class=\"prev\">Back to Overall Execution Summary</span></button>");
    pw.println("<br/><br/><br/><fieldset><legend><b>Testwise Overall Execution Details</b></legend><br/>"
            + "<table class=\"details\" cellspacing=0 cellpadding=0><tr><td><b>Module Name: </b></td><td>"
            + moduleVar + "</td></tr></table></fieldset><br/><br/>");

    moduleResults
            .append("<table id=\"myTable\" width=\"100%\" cellspacing=0 cellpadding=0 class=\"tablesorter\">");
    moduleResults.append("<thead><tr><th>Test Name</th> " +
    //"<th>Module</th> <th>Group</th>"+
            "<th>Browser</th> <th>Version</th> <th>OS</th>"
            + "<th>Node IP</th><th># Passed</th> <th># Failed</th> <th># Warning</th> <th># Skipped</th>"
            + "<th># Total</th> <th>Success Rate</th> </tr> </thead> <tbody>");

    int totalPassedMethods = 0;
    int totalFailedMethods = 0;
    int totalAutomationErrors = 0;
    int totalSkippedMethods = 0;

    String passPercentage = "";

    String suiteName = "";
    ITestContext overview = null;
    try {
        for (ISuite suite : suites) {
            suiteName = suite.getName();
            TestHelper.logger.info(">> " + suiteName + " <<");
            Map<String, ISuiteResult> tests = suite.getResults();

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

                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(2);
                nf.setGroupingUsed(true);

                passPercentage = getPercentage(nf, totalPassedMethods, totalPassedMethods + totalFailedMethods);

                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 (browser.equalsIgnoreCase("firefox")) {
                    browser = "Firefox";
                } else if (browser.equalsIgnoreCase("chrome")) {
                    browser = "Chrome";
                } else if (browser.equalsIgnoreCase("internet explorer")) {
                    browser = "IE";
                }

                if (platform.equalsIgnoreCase("xp")) {
                    platform = "XP";
                } else if (platform.equalsIgnoreCase("windows7")) {
                    platform = "Win 7";
                } else if (platform.equalsIgnoreCase("mac")) {
                    platform = "Mac";
                } else {

                }

                if (includedModule.equalsIgnoreCase(moduleVar)) {
                    String fileName = testName + "-customized-report.html";

                    if (nodeIp == null || nodeIp.trim().length() == 0) {
                        nodeIp = "?";
                    }

                    try {
                        generateModuleWiseTestReport(testName, suites, fileName, moduleVar, nodeIp);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

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

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

                    if (totalFailedMethods > 0) {
                        failCount = "<td bgcolor=\"" + failColor + "\"><font color=\"white\"><b>"
                                + totalFailedMethods + "</b></font></td>";
                    } else {
                        failCount = "<td>" + totalFailedMethods + "</td>";
                    }
                    if (totalAutomationErrors > 0) {
                        automationErrorCount = "<td bgcolor=\"" + warnColor + "\"><font color=\"white\"><b>"
                                + totalAutomationErrors + "</b></font></td>";
                    } else {
                        automationErrorCount = "<td>" + totalAutomationErrors + "</td>";
                    }
                    if (totalSkippedMethods > 0) {
                        skipCount = "<td bgcolor=\"" + skipColor + "\"><font color=\"white\"><b>"
                                + totalSkippedMethods + "</b></font></td>";
                    } else {
                        skipCount = "<td>" + totalSkippedMethods + "</td>";
                    }

                    moduleResults.append(
                            "<tr><td><b><a href=\"" + fileName + "\">" + testName + "</a></b></td>" + "<td>"
                            //+ includedModule + "</td><td>" + includedGroup + "</td><td>" 
                                    + browser + "</td><td>" + browser_version + "</td><td>" + platform
                                    + "</td><td>" + nodeIp + "</td>" + passCount + failCount
                                    + automationErrorCount + skipCount + "</td><td>"
                                    + (totalPassedMethods + totalFailedMethods + +totalAutomationErrors
                                            + totalSkippedMethods)
                                    + "</td><td><font color=\"" + passPercentageColor + "\"><b>"
                                    + passPercentage + " %" + "</b></font></td></tr>");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();//"Exception in report!!!: "+e);
    }

    moduleResults.append("</tbody></table>");
    pw.println(moduleResults);
    endHtmlPage(pw);
    pw.flush();
    pw.close();
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java

/**
 * Parses the given import xls file according to the users selection and creates/updates the
 * Preview table, showing the user how the import options effect the way the data will be
 * imported into the spreadsheet.//  ww  w .  j  a  v a  2s . co m
 * 
 * @param table - the table to display the data
 * @return JTable - the table to display the data
 */
private JTable setXLSTableData(final JTable table) {
    int numRows = 0;
    int numCols = 0;
    String[] headers = {};
    Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>();
    Vector<String> rowData = new Vector<String>();
    Vector<String> headerVector = new Vector<String>();
    DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat");
    try {
        log.debug("setXLSTableData - file - " + configXLS.getFile().toString());

        InputStream input = new FileInputStream(configXLS.getFile());
        POIFSFileSystem fs = new POIFSFileSystem(input);
        HSSFWorkbook workBook = new HSSFWorkbook(fs);
        HSSFSheet sheet = workBook.getSheetAt(0);

        Vector<Integer> badHeads = new Vector<Integer>();
        Vector<Integer> emptyCols = new Vector<Integer>();
        ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols);
        if (badHeads.size() > 0 && doesFirstRowHaveHeaders) {
            if (table != null) {
                ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle());
            }
            this.doesFirstRowHaveHeaders = false;
            try {
                ignoreActions = true;
                this.containsHeaders.setSelected(false);
            } finally {
                ignoreActions = false;
            }
            if (table != null) {
                return table;
            }
        }
        boolean firstRow = true;

        //quick fix to prevent ".0" at end of catalog numbers etc
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(20);
        nf.setGroupingUsed(false); //gets rid of commas

        int maxCols = 0;

        // Iterate over each row in the sheet
        Iterator<?> rows = sheet.rowIterator();
        while (rows.hasNext()) {
            numCols = 0;
            rowData = new Vector<String>();
            HSSFRow row = (HSSFRow) rows.next();
            //log.debug(row.getLastCellNum()+"  "+row.getPhysicalNumberOfCells());
            int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum());
            if (maxSize > maxCols) {
                maxCols = maxSize;
            }
            while (numCols < maxSize) {
                if (emptyCols.indexOf(new Integer(numCols)) == -1) {
                    HSSFCell cell = row.getCell(numCols);
                    String value = null;
                    // if cell is blank, set value to ""
                    if (cell == null) {
                        value = "";
                    } else {
                        int type = cell.getCellType();

                        switch (type) {
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            // The best I can do at this point in the app is to guess if a
                            // cell is a date.
                            // Handle dates carefully while using HSSF. Excel stores all
                            // dates as numbers, internally.
                            // The only way to distinguish a date is by the formatting of
                            // the cell. (If you
                            // have ever formatted a cell containing a date in Excel, you
                            // will know what I mean.)
                            // Therefore, for a cell containing a date, cell.getCellType()
                            // will return
                            // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility
                            // function,
                            // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell
                            // can be a date.
                            // This function checks the format against a few internal
                            // formats to decide the issue,
                            // but by its very nature it is prone to false negatives.
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                                //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue());
                            } else {
                                double numeric = cell.getNumericCellValue();
                                value = nf.format(numeric);
                            }
                            break;

                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getRichStringCellValue().getString();
                            break;

                        case HSSFCell.CELL_TYPE_BLANK:
                            value = "";
                            break;

                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = Boolean.toString(cell.getBooleanCellValue());
                            break;

                        case HSSFCell.CELL_TYPE_FORMULA:
                            value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW");
                            break;

                        default:
                            value = "";
                            log.error("unsuported cell type");
                            break;
                        }
                    }
                    if (firstRow && doesFirstRowHaveHeaders) {
                        checkUserColInfo(value, numCols);
                    }
                    if (isUserCol(numCols)) {
                        rowData.add(value.toString());
                    }
                }
                numCols++;
            }
            if (doesFirstRowHaveHeaders && firstRow) {
                headerVector = rowData;
                headers = new String[rowData.size()];
            } else if (!doesFirstRowHaveHeaders && firstRow) {
                //headers = createDummyHeaders(rowData.size());
                tableDataVector.add(rowData);
            } else {
                tableDataVector.add(rowData);
            }
            firstRow = false;
            numRows++;
        }
        maxCols -= emptyCols.size();
        if (!doesFirstRowHaveHeaders) {
            headerVector = createDummyHeadersAsVector(maxCols);
            headers = new String[maxCols];
        }
        for (int i = 0; i < headerVector.size(); i++) {
            headers[i] = headerVector.elementAt(i);
        }
        printArray(headers);

        String[][] tableData = new String[tableDataVector.size()][maxCols];
        for (int i = 0; i < tableDataVector.size(); i++) {
            Vector<String> v = tableDataVector.get(i);
            for (int j = 0; j < v.size(); j++) {
                tableData[i][j] = v.get(j).toString();
            }

        }
        if (checkForErrors(headers, tableData)) {
            errorPanel.showDataImportStatusPanel(true);
        } else {
            errorPanel.showDataImportStatusPanel(false);
        }

        if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) {
            hasTooManyRows = true;
            showTooManyRowsErrorDialog();
        } else {
            hasTooManyRows = false;
        }
        log.debug(headers);
        log.debug(tableData);
        model = new PreviewTableModel(headers, tableData);
        JTable result = null;
        if (table == null) {
            result = new JTable();
            result.setColumnSelectionAllowed(false);
            result.setRowSelectionAllowed(false);
            result.setCellSelectionEnabled(false);
            result.getTableHeader().setReorderingAllowed(false);
            result.setPreferredScrollableViewportSize(new Dimension(500, 100));
            result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        } else {
            result = table;
        }
        result.setModel(model);
        result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
        model.fireTableDataChanged();
        model.fireTableStructureChanged();
        return result;
    } catch (Exception ex) {
        UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE"));
        if (table != null) {
            String[] columnNames = {};
            String[][] blankData = { {} };
            model = new PreviewTableModel(columnNames, blankData);
            table.setModel(model);
            table.setColumnSelectionAllowed(false);
            table.setRowSelectionAllowed(false);
            table.setCellSelectionEnabled(false);
            table.getTableHeader().setReorderingAllowed(false);
            table.setPreferredScrollableViewportSize(new Dimension(500, 100));
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
            model.fireTableDataChanged();
            model.fireTableStructureChanged();
            return table;
        }
        //log.error("Error attempting to parse input xls file:" + ex);
        //ex.printStackTrace();
    }

    return null;
}

From source file:org.sakaiproject.util.impl.FormattedTextImpl.java

public NumberFormat getNumberFormat(Integer maxFractionDigits, Integer minFractionDigits,
        Boolean groupingUsed) {//from  w  w  w  .j  a  v  a  2  s  .  c o  m
    NumberFormat nbFormat = NumberFormat.getInstance();
    try {
        nbFormat = NumberFormat.getNumberInstance(new ResourceLoader().getLocale());
    } catch (Exception e) {
        M_log.error("Error while retrieving local number format, using default ", e);
    }
    if (maxFractionDigits != null)
        nbFormat.setMaximumFractionDigits(maxFractionDigits);
    if (minFractionDigits != null)
        nbFormat.setMinimumFractionDigits(minFractionDigits);
    if (groupingUsed != null)
        nbFormat.setGroupingUsed(groupingUsed);
    return nbFormat;
}