Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

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

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:org.yccheok.jstock.gui.NewSellTransactionJDialog.java

private JFormattedTextField getPercentageJFormattedTextField() {
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(2);
    format.setMinimumFractionDigits(2);/*from  ww  w .jav  a2s .c  om*/
    NumberFormatter formatter = new NumberFormatter(format);
    formatter.setValueClass(Double.class);
    JFormattedTextField formattedTextField = new JFormattedTextField(formatter);
    return formattedTextField;
}

From source file:org.yccheok.jstock.gui.NewSellTransactionJDialog.java

private JFormattedTextField getCurrencyJFormattedTextField(boolean isNegativeAllowed) {
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(4);
    NumberFormatter formatter = new NumberFormatter(format);

    if (isNegativeAllowed == false)
        formatter.setMinimum(0.0);/*w  w w . ja  va 2  s .c  o m*/
    else
        formatter.setMinimum(null);

    formatter.setValueClass(Double.class);
    JFormattedTextField formattedTextField = new JFormattedTextField(formatter);
    formattedTextField.addMouseListener(getJFormattedTextFieldMouseListener());
    return formattedTextField;
}

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   www  . j a  va 2 s  . c o  m
    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:org.codelibs.fess.web.IndexAction.java

protected String doSearchInternal() {
    final StringBuilder queryBuf = new StringBuilder(255);
    if (StringUtil.isNotBlank(indexForm.query)) {
        queryBuf.append(indexForm.query);
    }/*  w  w  w. j  a v a2s .c o m*/
    if (StringUtil.isNotBlank(indexForm.op)) {
        request.setAttribute(Constants.DEFAULT_OPERATOR, indexForm.op);
    }
    if (queryBuf.indexOf(" OR ") >= 0) {
        queryBuf.insert(0, '(').append(')');
    }
    if (indexForm.additional != null) {
        final Set<String> fieldSet = new HashSet<String>();
        for (final String additional : indexForm.additional) {
            if (StringUtil.isNotBlank(additional) && additional.length() < 1000
                    && !hasFieldInQuery(fieldSet, additional)) {
                queryBuf.append(' ').append(additional);
            }
        }
    }
    if (!indexForm.fields.isEmpty()) {
        for (final Map.Entry<String, String[]> entry : indexForm.fields.entrySet()) {
            final List<String> valueList = new ArrayList<String>();
            final String[] values = entry.getValue();
            if (values != null) {
                for (final String v : values) {
                    valueList.add(v);
                }
            }
            if (valueList.size() == 1) {
                queryBuf.append(' ').append(entry.getKey()).append(":\"").append(valueList.get(0)).append('\"');
            } else if (valueList.size() > 1) {
                queryBuf.append(" (");
                for (int i = 0; i < valueList.size(); i++) {
                    if (i != 0) {
                        queryBuf.append(" OR");
                    }
                    queryBuf.append(' ').append(entry.getKey()).append(":\"").append(valueList.get(i))
                            .append('\"');
                }
                queryBuf.append(')');
            }

        }
    }
    if (StringUtil.isNotBlank(indexForm.sort)) {
        queryBuf.append(" sort:").append(indexForm.sort);
    }
    if (indexForm.lang != null) {
        final Set<String> langSet = new HashSet<>();
        for (final String lang : indexForm.lang) {
            if (StringUtil.isNotBlank(lang) && lang.length() < 1000) {
                if (Constants.ALL_LANGUAGES.equalsIgnoreCase(lang)) {
                    langSet.add(Constants.ALL_LANGUAGES);
                } else {
                    final String normalizeLang = systemHelper.normalizeLang(lang);
                    if (normalizeLang != null) {
                        langSet.add(normalizeLang);
                    }
                }
            }
        }
        if (langSet.size() > 1 && langSet.contains(Constants.ALL_LANGUAGES)) {
            langSet.clear();
            indexForm.lang = new String[] { Constants.ALL_LANGUAGES };
        } else {
            langSet.remove(Constants.ALL_LANGUAGES);
        }
        appendLangQuery(queryBuf, langSet);
    } else if (Constants.TRUE.equals(
            crawlerProperties.getProperty(Constants.USE_BROWSER_LOCALE_FOR_SEARCH_PROPERTY, Constants.FALSE))) {
        final Set<String> langSet = new HashSet<>();
        final Enumeration<Locale> locales = request.getLocales();
        if (locales != null) {
            while (locales.hasMoreElements()) {
                final Locale locale = locales.nextElement();
                final String normalizeLang = systemHelper.normalizeLang(locale.toString());
                if (normalizeLang != null) {
                    langSet.add(normalizeLang);
                }
            }
            if (!langSet.isEmpty()) {
                appendLangQuery(queryBuf, langSet);
            }
        }
    }

    final String query = queryBuf.toString().trim();

    // init pager
    if (StringUtil.isBlank(indexForm.start)) {
        indexForm.start = String.valueOf(DEFAULT_START_COUNT);
    } else {
        try {
            Long.parseLong(indexForm.start);
        } catch (final NumberFormatException e) {
            indexForm.start = String.valueOf(DEFAULT_START_COUNT);
        }
    }
    if (StringUtil.isBlank(indexForm.num)) {
        indexForm.num = String.valueOf(getDefaultPageSize());
    }
    normalizePageNum();

    final int pageStart = Integer.parseInt(indexForm.start);
    final int pageNum = Integer.parseInt(indexForm.num);
    try {
        documentItems = searchService.getDocumentList(query, pageStart, pageNum, indexForm.facet, indexForm.geo,
                indexForm.mlt, queryHelper.getResponseFields(), queryHelper.getResponseDocValuesFields());
    } catch (final SolrLibQueryException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, "errors.invalid_query_unknown");
    } catch (final InvalidQueryException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, e.getMessageCode());
    } catch (final ResultOffsetExceededException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        throw new SSCActionMessagesException(e, "errors.result_size_exceeded");
    }
    // search
    final QueryResponseList queryResponseList = (QueryResponseList) documentItems;
    facetResponse = queryResponseList.getFacetResponse();
    moreLikeThisResponse = queryResponseList.getMoreLikeThisResponse();
    final NumberFormat nf = NumberFormat.getInstance(RequestUtil.getRequest().getLocale());
    nf.setMaximumIntegerDigits(2);
    nf.setMaximumFractionDigits(2);
    try {
        execTime = nf.format((double) queryResponseList.getExecTime() / 1000);
    } catch (final Exception e) {
        // ignore
    }

    final Clock clock = Clock.systemDefaultZone();
    indexForm.rt = Long.toString(clock.millis());

    // favorite
    if (favoriteSupport || screenShotManager != null) {
        indexForm.queryId = userInfoHelper.generateQueryId(query, documentItems);
        if (screenShotManager != null) {
            screenShotManager.storeRequest(indexForm.queryId, documentItems);
            screenShotSupport = true;
        }
    }

    // search log
    if (searchLogSupport) {
        final LocalDateTime now = systemHelper.getCurrentTime();

        final SearchLogHelper searchLogHelper = ComponentUtil.getSearchLogHelper();
        final SearchLog searchLog = new SearchLog();

        String userCode = null;
        if (Constants.TRUE
                .equals(crawlerProperties.getProperty(Constants.USER_INFO_PROPERTY, Constants.TRUE))) {
            userCode = userInfoHelper.getUserCode();
            if (StringUtil.isNotBlank(userCode)) {
                final UserInfo userInfo = new UserInfo();
                userInfo.setCode(userCode);
                userInfo.setCreatedTime(now);
                userInfo.setUpdatedTime(now);
                searchLog.setUserInfo(OptionalEntity.of(userInfo));
            }
        }

        searchLog.setHitCount(queryResponseList.getAllRecordCount());
        searchLog.setResponseTime(Integer.valueOf((int) queryResponseList.getExecTime()));
        searchLog.setSearchWord(StringUtils.abbreviate(query, 1000));
        searchLog.setSearchQuery(StringUtils.abbreviate(queryResponseList.getSearchQuery(), 1000));
        searchLog.setSolrQuery(StringUtils.abbreviate(queryResponseList.getSolrQuery(), 1000));
        searchLog.setRequestedTime(now);
        searchLog.setQueryOffset(pageStart);
        searchLog.setQueryPageSize(pageNum);

        searchLog.setClientIp(StringUtils.abbreviate(request.getRemoteAddr(), 50));
        searchLog.setReferer(StringUtils.abbreviate(request.getHeader("referer"), 1000));
        searchLog.setUserAgent(StringUtils.abbreviate(request.getHeader("user-agent"), 255));
        if (userCode != null) {
            searchLog.setUserSessionId(userCode);
        }
        final Object accessType = request.getAttribute(Constants.SEARCH_LOG_ACCESS_TYPE);
        if (accessType instanceof CDef.AccessType) {
            switch ((CDef.AccessType) accessType) {
            case Json:
                searchLog.setAccessType_Json();
                searchLog.setAccessType_Others();
                searchLog.setAccessType_Xml();
                break;
            case Xml:
                searchLog.setAccessType_Xml();
                break;
            case Others:
                searchLog.setAccessType_Others();
                break;
            default:
                searchLog.setAccessType_Web();
                break;
            }
        } else {
            searchLog.setAccessType_Web();
        }

        @SuppressWarnings("unchecked")
        final Map<String, List<String>> fieldLogMap = (Map<String, List<String>>) request
                .getAttribute(Constants.FIELD_LOGS);
        if (fieldLogMap != null) {
            for (final Map.Entry<String, List<String>> logEntry : fieldLogMap.entrySet()) {
                for (final String value : logEntry.getValue()) {
                    searchLog.addSearchFieldLogValue(logEntry.getKey(), StringUtils.abbreviate(value, 1000));
                }
            }
        }

        searchLogHelper.addSearchLog(searchLog);
    }

    final String[] highlightQueries = (String[]) request.getAttribute(Constants.HIGHLIGHT_QUERIES);
    if (highlightQueries != null) {
        final StringBuilder buf = new StringBuilder(100);
        for (final String q : highlightQueries) {
            buf.append("&hq=").append(q);
        }
        appendHighlightQueries = buf.toString();
    }

    Beans.copy(documentItems, this)
            .includes("pageSize", "currentPageNumber", "allRecordCount", "allPageCount", "existNextPage",
                    "existPrevPage", "currentStartRecordNumber", "currentEndRecordNumber", "pageNumberList",
                    "partialResults", "queryTime", "searchTime")
            .execute();

    return query;
}

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 2s .  co 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;
}

From source file:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private void logDownloadSize(long size) {
    if (logger.isInfoEnabled()) {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(2);
        String suffix = "kb";
        float factor = 1024;
        if (size > 1024 * 1024) {
            suffix = "mb";
            factor = 1024 * 1024;/*from ww  w. j ava 2s.  c o m*/
        }
        logger.info("Downloaded [" + nf.format(size / factor) + suffix + "] to [" + deployPath + "]");
    }
}

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  a  v  a2s  . c om*/

    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:canreg.client.analysis.AgeSpecificCasesTableBuilder.java

@Override
public LinkedList<String> buildTable(String registryLabel, String reportFileName, int startYear, int endYear,
        Object[][] incidenceData, PopulationDataset[] populations, PopulationDataset[] standardPopulations,
        LinkedList<ConfigFields> configList, String[] engineParameters, FileTypes fileType)
        throws NotCompatibleDataException {

    LinkedList<String> generatedFiles = new LinkedList<String>();

    String footerString = java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
            .getString("TABLE BUILT ")
            + new Date()
            + java.util.ResourceBundle
                    .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                    .getString(" BY CANREG5.");

    String notesString = "";

    if (populations[0].getFilter().length() > 0) {
        notesString = java.util.ResourceBundle
                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                .getString("FILTER USED:") + " " + populations[0].getFilter();
    }//from  w w  w  .  j av a 2  s. c  o m

    double tableFontSize = 7.5;
    String font = "Times";

    int[] years = { startYear, endYear };

    //      double RegPop[][];
    double totalCases[][];

    String sexLabel[] = null;
    String tableLabel[] = null;
    String icdLabel[] = null;

    LinkedList cancerGroupsLocal[] = null;

    boolean showSeeNotesNote = true;

    char Childc[][] = new char[2][3];

    double casesPerHundredThousand[][][];

    double cumRate64[][];
    double cumRate74[][];

    tableLabel = ConfigFieldsReader.findConfig("table_label", configList);
    // sexLabel = ConfigFieldsReader.findConfig("sex_label", configList);
    sexLabel = new String[] {
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("MALE"),
            java.util.ResourceBundle.getBundle("canreg/client/analysis/resources/AbstractEditorialTableBuilder")
                    .getString("FEMALE") };

    icdLabel = ConfigFieldsReader.findConfig("ICD_groups_labels", configList);
    icd10GroupDescriptions = ConfigFieldsReader.findConfig("ICD10_groups", configList);

    cancerGroupsLocal = EditorialTableTools.generateICD10Groups(icd10GroupDescriptions);

    allCancerGroupsIndex = EditorialTableTools.getICD10index("ALL", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    skinCancerGroupIndex = EditorialTableTools.getICD10index("C44", icd10GroupDescriptions);

    bladderCancerGroupIndex = EditorialTableTools.getICD10index("C67", icd10GroupDescriptions);

    mesotheliomaCancerGroupIndex = EditorialTableTools.getICD10index("C45", icd10GroupDescriptions);

    kaposiSarkomaCancerGroupIndex = EditorialTableTools.getICD10index("C46", icd10GroupDescriptions);

    myeloproliferativeDisordersCancerGroupIndex = EditorialTableTools.getICD10index("MPD",
            icd10GroupDescriptions);

    myelodysplasticSyndromesCancerGroupIndex = EditorialTableTools.getICD10index("MDS", icd10GroupDescriptions);

    allCancerGroupsButSkinIndex = EditorialTableTools.getICD10index("ALLbC44", icd10GroupDescriptions);

    leukemiaNOSCancerGroupIndex = EditorialTableTools.getICD10index(950, cancerGroupsLocal);

    brainAndCentralNervousSystemCancerGroupIndex = EditorialTableTools.getICD10index("C70-72",
            icd10GroupDescriptions);

    ovaryCancerGroupIndex = EditorialTableTools.getICD10index(569, cancerGroupsLocal);

    otherCancerGroupsIndex = EditorialTableTools.getICD10index("O&U", icd10GroupDescriptions);

    numberOfCancerGroups = cancerGroupsLocal.length;

    lineBreaks = parseLineBreaks(ConfigFieldsReader.findConfig("line_breaks", configList));

    numberOfYears = years[1] - years[0] + 1;

    minimumCasesLimit = minimumCasesPerYearLimit * numberOfYears;

    noOldData = true;

    casesPerHundredThousand = new double[numberOfSexes][numberOfAgeGroups][numberOfCancerGroups];

    casesArray = new double[numberOfCancerGroups][numberOfSexes][numberOfAgeGroups];

    // cumRate64 = new double[numberOfSexes][numberOfCancerGroups];
    // cumRate74 = new double[numberOfSexes][numberOfCancerGroups];
    populationArray = new double[numberOfSexes][numberOfAgeGroups];
    foundAgeGroups = new boolean[numberOfAgeGroups];

    if (areThesePopulationDatasetsCompatible(populations)) {
        for (PopulationDataset population : populations) {
            population.addPopulationDataToArrayForTableBuilder(populationArray, foundAgeGroups,
                    new AgeGroupStructure(5, 85, 1));
        }
    } else {
        throw new NotCompatibleDataException();
    }

    populationString = populations[0].getPopulationDatasetName();

    int lastCommaPlace = populationString.lastIndexOf(",");

    if (lastCommaPlace != -1) {
        populationString = populationString.substring(0, lastCommaPlace);
    }

    if (populations[0].getFilter().length() > 0) {
        notesString = java.util.ResourceBundle
                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                .getString("FILTER USED:") + populations[0].getFilter();
    }

    standardPopulationArray = new double[numberOfSexes][numberOfAgeGroups];

    for (PopulationDataset stdPopulation : standardPopulations) {
        stdPopulation.addPopulationDataToArrayForTableBuilder(standardPopulationArray, null,
                new AgeGroupStructure(5, 85, 1));
    }

    // standardize population array
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int ageGroupNumber = 0; ageGroupNumber < numberOfAgeGroups; ageGroupNumber++) {
            standardPopulationArray[sexNumber][ageGroupNumber] = (standardPopulationArray[sexNumber][ageGroupNumber]
                    / standardPopulationArray[sexNumber][numberOfAgeGroups - 1]) * 100000;
        }
    }

    highestPopulationAgeGroup = findHighestAgeGroup(foundAgeGroups);
    lowestPopulationAgeGroup = findLowestAgeGroup(foundAgeGroups);

    int records = 0;
    // generate statistics

    String sexString;
    String icdString;
    String yearString;
    String ageString;
    String basisString;

    int sex, icdNumber, year, icdIndex, yearIndex, ageGroup, ageInt, basis, cases;

    if (incidenceData != null) {
        for (Object[] line : incidenceData) {
            try {
                // Set default
                icdIndex = -1;
                cases = 0;

                // Unknown sex group = 3
                sex = 3;
                // Extract data
                sexString = (String) line[SEX_COLUMN];
                sex = Integer.parseInt(sexString.trim());

                // sex = 3 is unknown sex
                if (sex > 2) {
                    sex = 3;
                }

                // morphologyString = (String) line[MORPHOLOGY_COLUMN];

                /*
                if (morphologyString.length() > 0) {
                int morphology = Integer.parseInt(morphologyString);
                if (morphology == 9140) {
                String behaviourString = getContentOfField(
                incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = kaposiSarkomaCancerGroupIndex;
                }
                        
                } else if ((int)(morphology/10) == 905) {
                String behaviourString = getContentOfField(incidenceFieldDescriptionList,
                "behaviour", line).trim();
                if (behaviourString.equals("3")) {
                icdIndex = mesotheliomaCancerGroupIndex;
                }
                }
                }
                 */
                if (icdIndex < 0) {
                    icdString = (String) line[ICD10_COLUMN];
                    if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("C")) {
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        icdIndex = EditorialTableTools.getICD10index(icdNumber, cancerGroupsLocal);
                        if (icdIndex == -1) {
                            icdIndex = -1;
                        }
                    } else if (icdString.length() > 0 && icdString.trim().substring(0, 1).equals("D")) {
                        icdIndex = DONT_COUNT; // set don't count as default
                        icdString = icdString.trim().substring(1);
                        icdNumber = Integer.parseInt(icdString);
                        if (icdString.length() < 3) {
                            icdNumber = icdNumber * 10;
                        }
                        if (icdNumber == 90 || icdNumber == 414) {
                            icdIndex = bladderCancerGroupIndex;
                        } else if (((int) (icdNumber / 10)) == 45 || ((int) (icdNumber / 10)) == 47) {
                            icdIndex = myeloproliferativeDisordersCancerGroupIndex;
                        } else if (((int) (icdNumber / 10)) == 46) {
                            icdIndex = myelodysplasticSyndromesCancerGroupIndex;
                        }
                    }
                }

                yearString = line[YEAR_COLUMN].toString();
                year = Integer.parseInt(yearString);
                yearIndex = year - years[0];
                ageString = line[AGE_COLUMN].toString();
                ageInt = Integer.parseInt(ageString);

                if (ageInt == unknownAgeInt) {
                    ageGroup = unknownAgeGroupIndex;
                } else {
                    ageGroup = populations[yearIndex].getAgeGroupIndex(ageInt);
                    // Adjust age group
                    if (populations[yearIndex].getAgeGroupStructure().getSizeOfFirstGroup() != 1) {
                        ageGroup += 1;
                    }
                }

                // Extract cases
                cases = (Integer) line[CASES_COLUMN];

                if (icdIndex != DONT_COUNT && year <= years[1] && year >= years[0]) {

                    // Basis of diagnosis
                    basisString = line[BASIS_DIAGNOSIS_COLUMN].toString();
                    if (basisString != null) {
                        basis = Integer.parseInt(basisString.trim());
                    } else {
                        basis = -1;
                    }

                    if (sex <= numberOfSexes && icdIndex >= 0 && icdIndex <= cancerGroupsLocal.length) {

                        casesArray[icdIndex][sex - 1][ageGroup] += cases;

                    } else if (otherCancerGroupsIndex >= 0) {
                        casesArray[otherCancerGroupsIndex][sex - 1][ageGroup] += cases;
                    }
                    if (allCancerGroupsIndex >= 0) {
                        casesArray[allCancerGroupsIndex][sex - 1][ageGroup] += cases;
                    }
                    if (allCancerGroupsButSkinIndex >= 0 && skinCancerGroupIndex >= 0
                            && icdIndex != skinCancerGroupIndex) {
                        casesArray[allCancerGroupsButSkinIndex][sex - 1][ageGroup] += cases;
                    }
                    records += cases;
                    if (records % recordsPerFeedback == 0) {
                        System.out.println(java.util.ResourceBundle
                                .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                                .getString("PROCESSING RECORD NUMBER: ") + records);
                    }
                }
            } catch (NumberFormatException nfe) {
                Logger.getLogger(AgeSpecificCasesTableBuilder.class.getName()).log(Level.WARNING, null, nfe);
            }
            // Read next line
        }
    }
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder").getString("PROCESSED ")
            + records
            + java.util.ResourceBundle
                    .getBundle("canreg/client/analysis/resources/AgeSpecificCasesTableBuilder")
                    .getString(" RECORDS."));

    // Total casesPerHundredThousand
    totalCases = new double[numberOfSexes][numberOfCancerGroups];
    // Crude rate
    // crudeRate = new double[numberOfSexes][numberOfCancerGroups];

    for (int sexNumber = 0; sexNumber < 2; sexNumber++) {

        // The age groups
        ageLabel[lowestPopulationAgeGroup] = "0-";

        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {
            if (icdLabel[icdGroup].substring(0 + sexNumber, 1 + sexNumber).equalsIgnoreCase("1")) {
                // The age groups

                double previousAgeGroupCases = 0;
                double previousAgeGroupPopulation = 0;
                double previousAgeGroupWstdPopulation = 0;

                double lastAgeGroupCases = 0;
                double lastAgeGroupPopulation = 0;
                double lastAgeGroupWstdPopulation = 0;

                for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                    if (ageGroupNumber == 1) {
                        for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                            previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                            previousAgeGroupPopulation += populationArray[sexNumber][ag];
                            previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                        }
                    }
                    if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup) {
                        casesPerHundredThousand[sexNumber][ageGroupNumber][icdGroup] = 100000
                                * (casesArray[icdGroup][sexNumber][ageGroupNumber] + previousAgeGroupCases)
                                / (populationArray[sexNumber][ageGroupNumber] + previousAgeGroupPopulation);

                        previousAgeGroupCases = 0;
                        previousAgeGroupPopulation = 0;
                        previousAgeGroupWstdPopulation = 0;

                    } else {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                        previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                    }
                }
                // We calculate the "leftovers" from the last age group
                if (previousAgeGroupPopulation > 0) {
                    casesPerHundredThousand[sexNumber][highestPopulationAgeGroup][icdGroup] = 100000
                            * (previousAgeGroupCases) / (previousAgeGroupPopulation);

                }

                previousAgeGroupCases = 0;
                previousAgeGroupPopulation = 0;
                previousAgeGroupWstdPopulation = 0;

            }
        }
    }

    // ASR, vASR, MV, MI, DCO
    for (int sexNumber = 0; sexNumber < numberOfSexes; sexNumber++) {
        for (int icdGroup = 0; icdGroup < numberOfCancerGroups; icdGroup++) {

            double previousAgeGroupCases = 0;
            double previousAgeGroupPopulation = 0;
            double previousAgeGroupWstdPopulation = 0;

            double lastAgeGroupCases = 0;
            double lastAgeGroupPopulation = 0;
            double lastAgeGroupWstdPopulation = 0;

            totalCases[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][0];

            for (int ageGroupNumber = 1; ageGroupNumber < unknownAgeGroupIndex; ageGroupNumber++) {
                if (ageGroupNumber == 1) {
                    for (int ag = lowestIncidenceAgeGroup; ag < ageGroupNumber; ag++) {
                        previousAgeGroupCases += casesArray[icdGroup][sexNumber][ag];
                        previousAgeGroupPopulation += populationArray[sexNumber][ag];
                        previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ag];
                    }
                }
                if (foundAgeGroups[ageGroupNumber] && ageGroupNumber < highestPopulationAgeGroup
                        && (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber] > 0)) {
                    double asr = calculateASR(
                            (previousAgeGroupCases + casesArray[icdGroup][sexNumber][ageGroupNumber]),
                            (previousAgeGroupPopulation + populationArray[sexNumber][ageGroupNumber]),
                            (previousAgeGroupWstdPopulation
                                    + standardPopulationArray[sexNumber][ageGroupNumber]));

                    previousAgeGroupCases = 0;
                    previousAgeGroupPopulation = 0;
                    previousAgeGroupWstdPopulation = 0;

                } else if (ageGroupNumber < highestPopulationAgeGroup) {
                    previousAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    previousAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    previousAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];

                } else {
                    lastAgeGroupCases += casesArray[icdGroup][sexNumber][ageGroupNumber];
                    lastAgeGroupPopulation += populationArray[sexNumber][ageGroupNumber];
                    lastAgeGroupWstdPopulation += standardPopulationArray[sexNumber][ageGroupNumber];
                }

                totalCases[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][ageGroupNumber];
            }

            // We calculate the "leftovers" from the last age group
            if (lastAgeGroupPopulation > 0) {
                double asr = calculateASR(lastAgeGroupCases, lastAgeGroupPopulation,
                        lastAgeGroupWstdPopulation);

            }

            // and take the unknown age group into account
            totalCases[sexNumber][icdGroup] += casesArray[icdGroup][sexNumber][unknownAgeGroupIndex];

            if (totalCases[sexNumber][icdGroup] > 0) {

                /* We don't use confidence intervals so this was removed 16.07.07
                double[] asrlul = calculateASRluL(ASR[sex][icdGroup],
                variL[sex][icdGroup], wstdPop[allAgeGroupsIndex]);
                        
                ASRluL[sex][icdGroup][0] = asrlul[0];
                ASRluL[sex][icdGroup][1] = asrlul[1];
                 */
                // Cum. Rates
                if (highestPopulationAgeGroup > 13) {
                    for (int k = 1; k <= 13; k++) {
                        // cumRate64[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup] * cumPop18[k] / 1000.0;
                    }
                }
                if (highestPopulationAgeGroup > 15) {
                    for (int k = 1; k <= 15; k++) {
                        // cumRate74[sexNumber][icdGroup] += casesPerHundredThousand[sexNumber][k][icdGroup] * cumPop18[k] / 1000.0;
                    }
                }

                /*                    if (!isSpecialized) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                if (icdGroup!=skinCancerGroupIndex) {
                cumRate64[sex][allCancerGroupsIndex] += cumRate64[sex][icdGroup];
                cumRate74[sex][allCancerGroupsIndex] += cumRate74[sex][icdGroup];
                }
                }
                 */
            }
        }
    }

    // Adjust the age labels
    ageLabel[1] = "0-";
    ageLabel[highestPopulationAgeGroup] = ageLabel[highestPopulationAgeGroup].substring(0,
            ageLabel[highestPopulationAgeGroup].length() - 1) + "+";

    // Write it out
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(1);
    nf.setMinimumFractionDigits(1);

    Writer reportFileWriter;

    if (fileType.equals(FileTypes.csv)) {
        // write tab separated stuff here
        CSVPrinter csvOut;
        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            try {
                String tabReportFileName = "";
                try {
                    tabReportFileName = reportFileName + sexLabel[sexNumber] + ".csv";
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("WRITING TO ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(new FileOutputStream(tabReportFileName), "UTF-8");
                } catch (IOException ioe) {
                    System.out.println(java.util.ResourceBundle.getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                            .getString("ERROR IN REPORTFILE: ") + tabReportFileName);
                    reportFileWriter = new OutputStreamWriter(System.out);
                }
                // reportStream = new PrintStream(tabReportFileName);
                // write the header line
                // reportStream = new PrintStream(tabReportFileName);
                // write the header line
                LinkedList<String> headers = new LinkedList<String>();
                headers.add("SITE");
                headers.add("ALL AGES");
                headers.add("AGE UNK");
                // add age groups

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    headers.add(ageLabel[age]);
                }

                // headers.add("CRUDE RATE");
                headers.add("(%)");
                //                    headers.add("CUM 0-64");
                //                    headers.add("CUM 0-74");
                //                    headers.add("ASR");
                headers.add("ICD (10th)");

                CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',')
                        .withHeader(headers.toArray(new String[0]));

                csvOut = new CSVPrinter(reportFileWriter, format);

                LinkedList<String> line = new LinkedList<String>();

                // write the data
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        line.add(icdLabel[j].substring(3));
                        line.add(formatNumber(totalCases[sexNumber][j], 0));
                        line.add(formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0));
                        for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                            if (casesArray[j][sexNumber][age] > 0) {
                                line.add(formatNumber(casesArray[j][sexNumber][age], 0));
                            } else {
                                line.add("0");
                            }
                        }
                        // line.add(formatNumber(crudeRate[sexNumber][j], 2));
                        line.add(formatNumber(100 * totalCases[sexNumber][j]
                                / totalCases[sexNumber][allCancerGroupsButSkinIndex]));
                        // line.add(formatNumber(cumRate64[sexNumber][j], 2));
                        // line.add(formatNumber(cumRate74[sexNumber][j], 2));
                        // line.add(formatNumber(ASR[sexNumber][j]));
                        line.add(icd10GroupDescriptions[j]);
                        csvOut.printRecord(line);
                        line.clear();
                    }
                }

                try {
                    csvOut.flush();
                    csvOut.close();
                } catch (IOException ex) {
                    Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
                generatedFiles.add(tabReportFileName);
            } catch (IOException ex) {
                Logger.getLogger(AgeSpecificCasesTableBuilder.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {

        // Make PS-file
        for (int sexNumber = 0; sexNumber < numberOfSexes - 1; sexNumber++) {
            String psFileName = reportFileName + "-" + sexLabel[sexNumber] + ".ps";
            generatedFiles.add(psFileName);
            try {
                Writer fw = new OutputStreamWriter(new FileOutputStream(psFileName), "UTF-8");

                nf.setMaximumFractionDigits(1);
                nf.setMinimumFractionDigits(1);

                fw.write("/RLT {rlineto} def\n");
                fw.write("/LT {lineto} def\n");
                fw.write("/MT {moveto} def\n");
                fw.write("/SCF {scalefont} def\n");
                fw.write("/SF {setfont} def\n");
                fw.write("/SG {setgray} def\n");
                fw.write("/FF {findfont} def\n");
                fw.write("/SLW {setlinewidth} def\n");
                fw.write("/CP {closepath} def\n");
                fw.write("/Mainfont\n");
                fw.write("/Helvetica-Bold FF " + (int) (tableFontSize * 2 - 3) + " SCF def\n");
                fw.write("/Titlefont\n");
                fw.write("/Helvetica FF " + tableFontSize + " SCF def\n");
                fw.write("/Tablefont\n");
                fw.write("/" + font + " FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRfont\n");
                fw.write("/" + font + "-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/ICDfont\n");
                fw.write("/" + font + "-Italic FF " + tableFontSize + " SCF def\n");
                fw.write("/ASRitalicsfont\n");
                fw.write("/" + font + "-Italic-Bold FF " + tableFontSize + " SCF def\n");
                fw.write("/col 735 def\n");
                fw.write("/RS {dup stringwidth pop col exch sub 0 rmoveto show} def\n");
                fw.write("/CS {dup stringwidth pop 810 exch sub 2 div 0 rmoveto show} def\n");
                fw.write("/nstr 1 string def\n");
                fw.write("/prtchar {nstr 0 3 -1 roll put nstr show} def\n");
                fw.write("newpath\n");
                fw.write("90 rotate -20 -570 translate\n"); //  Landscape
                fw.write("Mainfont SF\n");
                fw.write("0 535 MT (" + registryLabel + ") CS\n");
                fw.write("Titlefont SF\n");
                fw.write("0 525 MT (" + populationString + ") CS\n");
                fw.write("0 513 MT (" + tableLabel[0] + " - " + sexLabel[sexNumber] + ") CS\n");
                //                                                                                              draw the grey frame
                fw.write("0.85 SG 27 510 translate\n");
                fw.write("0 -5 MT 785 -5 LT 785 -27 LT 0 -27 LT  CP fill\n");
                fw.write("0 -510 translate 0.95 SG\n");
                double k = 475;

                for (int icd = 0; icd < numberOfCancerGroups; icd++) {
                    if ((icd + 1) < numberOfCancerGroups && icdLabel[icd + 1].charAt(sexNumber) == '1') {
                        int lines = (isLineBreak(icd));
                        if (lines > 0) {
                            k -= 2;
                            fw.write("0 " + (k - 2) + " MT 785 " + (k - 2) + " LT 785 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT 0 "
                                    + (k - 2 - (lines * (tableFontSize))) + " LT CP fill\n");
                        } else if (lines < 0) {
                            k -= 2;
                        }
                        k -= tableFontSize;
                    }
                }

                /*
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '1') {
                        
                int lines = (isLineBreak(j));
                if (lines > 0) {
                k -= 2;
                        
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - lines * tableFontSize) + " LT 0 " + (k - lines * tableFontSize) +
                " LT CP fill\n");
                        
                } else if (lines > 0)
                k -= 2;
                k -= lines * tableFontSize;
                        
                        
                        
                        
                if (IsLineBreak(j)) {
                k -= 2;
                }
                //  draw the grey frames
                if (j == 8) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 35) + " LT 0 " + (k - 35) +
                " LT CP fill\n");
                } else if (j == 34) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 26) + " LT 0 " + (k - 26) +
                " LT CP fill\n");
                } else if (j == 16 || j == 22 || j == 40) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 18) + " LT 0 " + (k - 18) +
                " LT CP fill\n");
                } else if (j == 27) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 42) + " LT 0 " + (k - 42) +
                " LT CP fill\n");
                } else if (j == 47) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 34) + " LT 0 " + (k - 34) +
                " LT CP fill\n");
                } else if (j == 53) {
                fw.write(
                "0 " + (k + tableFontSize) + " MT 774 " + (k + tableFontSize) +
                " LT 774 " + (k - 12) + " LT 0 " + (k - 12) +
                " LT CP fill\n");
                }
                k -= (tableFontSize);
                }
                        
                }
                 */
                fw.write("0 SG\n");

                fw.write("ICDfont SF\n");
                fw.write(" 740 496 MT (ICD) show\n");
                fw.write(" 740 487 MT ((10th)) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("ICDfont SF\n");
                        }

                        fw.write("745 " + k + " MT (" + icd10GroupDescriptions[j] + ") show\n");
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("0 491 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }

                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        if (j != allCancerGroupsIndex && allCancerGroupsButSkinIndex >= 0) {
                            fw.write(
                                    "0 " + k + " MT ("
                                            + formatNumber(100 * totalCases[sexNumber][j]
                                                    / totalCases[sexNumber][allCancerGroupsButSkinIndex])
                                            + ") RS\n");
                        }
                        k -= (tableFontSize);
                    }
                }

                fw.write("/col 119 def\n");
                fw.write("0 496 MT (ALL) RS\n");
                fw.write("0 487 MT (AGES) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT (" + formatNumber(totalCases[sexNumber][j], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 add def\n");
                fw.write("0 496 MT (AGE) RS\n");
                fw.write("0 487 MT (UNK) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("0 " + k + " MT ("
                                + formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }

                if (highestPopulationAgeGroup == numberOfAgeGroups - 4) {
                    fw.write("/col 145 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 5) {
                    fw.write("/col 176 def\n");
                } else if (highestPopulationAgeGroup == numberOfAgeGroups - 6) {
                    fw.write("/col 208 def\n");
                } else {
                    fw.write("/col 145 def\n");
                }

                for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                    fw.write("/col col 26 add def\n");
                    fw.write("0 491 MT (" + ageLabel[age] + ") RS\n");
                    // fw.write("/col col 5 sub def\n");
                    k = 475;
                    for (int j = 0; j < numberOfCancerGroups; j++) {
                        if (icdLabel[j].charAt(sexNumber) == '1') {
                            if (isLineBreak(j - 1) != 0) {
                                k -= 2;
                            }

                            if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                    || j == bladderCancerGroupIndex
                                    || j == myelodysplasticSyndromesCancerGroupIndex
                                    || j == myeloproliferativeDisordersCancerGroupIndex
                                    || j == brainAndCentralNervousSystemCancerGroupIndex) {
                                fw.write("ICDfont SF\n");
                            } else {
                                fw.write("Tablefont SF\n");
                            }

                            if (casesArray[j][sexNumber][age] > 0) {
                                fw.write("0 " + k + " MT (" + formatNumber(casesArray[j][sexNumber][age], 0)
                                        + ") RS\n");
                            } else {
                                fw.write("0 " + k + " MT (    -  ) RS\n");
                            }
                            k -= (tableFontSize);
                        }
                    }
                }
                fw.write("3 492 MT ( S I T E) show\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                    if (icdLabel[j].charAt(sexNumber) == '1') {
                        if (isLineBreak(j - 1) != 0) {
                            k -= 2;
                        }
                        if (j == skinCancerGroupIndex || j == ovaryCancerGroupIndex
                                || j == bladderCancerGroupIndex || j == myelodysplasticSyndromesCancerGroupIndex
                                || j == myeloproliferativeDisordersCancerGroupIndex
                                || j == brainAndCentralNervousSystemCancerGroupIndex) {
                            fw.write("ICDfont SF\n");
                        } else {
                            fw.write("Tablefont SF\n");
                        }

                        fw.write("3 " + k + " MT (" + icdLabel[j].substring(3) + ") show\n");
                        k -= (tableFontSize);
                    }
                }
                if (showSeeNotesNote) {
                    fw.write("3 0 MT (" + notesString + ") show\n");
                }

                // Write the footer
                fw.write("0 0 MT (" + footerString + ") CS\n");

                fw.write("showpage\n");
                System.out.println("Wrote " + psFileName + ".");
                fw.close();
            } catch (IOException ioe) {
                System.out.println(ioe);
            }
        }
    }

    if (fileType == FileTypes.pdf) {
        LinkedList<String> newlyGeneratedFiles = new LinkedList<String>();
        for (String fileN : generatedFiles) {
            PsToPdfConverter pstopdf = new PsToPdfConverter(gspath);
            newlyGeneratedFiles.add(pstopdf.convert(fileN));
            // delete the ps file
            File file = new File(fileN);
            file.delete();
        }
        generatedFiles = newlyGeneratedFiles;
    }

    System.out.println("Fini!");

    return generatedFiles;
}

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  . j a v a2 s.  c  o 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.//from  w  w  w .  j a  v  a2s .  c om
 * 
 * @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;
}