Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

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

Prototype

public static final NumberFormat getInstance() 

Source Link

Document

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

Usage

From source file:com.glaf.core.jdbc.QueryHelper.java

/**
 * @param conn//from w ww  .java  2s.  co m
 *            ?
 * @param start
 *            0
 * @param pageSize
 *            ?
 * @param sql
 *            ?
 * @param paramMap
 *            ?
 * @return
 */
@SuppressWarnings("unchecked")
public ResultModel getResultList(Connection conn, String sql, Map<String, Object> paramMap, int start,
        int pageSize) {
    if (!DBUtils.isLegalQuerySql(sql)) {
        throw new RuntimeException(" SQL statement illegal ");
    }
    ResultModel resultModel = new ResultModel();
    boolean supportsPhysicalPage = false;
    PreparedStatement psmt = null;
    ResultSetMetaData rsmd = null;
    ResultSet rs = null;
    Dialect dialect = null;
    try {
        dialect = DBConfiguration.getDatabaseDialect(conn);
        if (dialect != null && dialect.supportsPhysicalPage()) {
            logger.debug("sql=" + sql);
            supportsPhysicalPage = dialect.supportsPhysicalPage();
            sql = dialect.getLimitString(sql, start, pageSize);
            logger.debug(">>sql=" + sql);
        }

        List<Object> values = null;
        if (paramMap != null) {
            SqlExecutor sqlExecutor = DBUtils.replaceSQL(sql, paramMap);
            sql = sqlExecutor.getSql();
            values = (List<Object>) sqlExecutor.getParameter();
        }

        logger.debug("sql:\n" + sql);
        logger.debug("values:" + values);

        psmt = conn.prepareStatement(sql);

        if (values != null && !values.isEmpty()) {
            JdbcUtils.fillStatement(psmt, values);
        }

        List<ColumnDefinition> columns = new ArrayList<ColumnDefinition>();
        rs = psmt.executeQuery();
        rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            int sqlType = rsmd.getColumnType(i);
            ColumnDefinition column = new ColumnDefinition();
            column.setIndex(i);
            column.setColumnName(rsmd.getColumnName(i));
            column.setColumnLabel(rsmd.getColumnLabel(i));
            column.setJavaType(FieldType.getJavaType(sqlType));
            column.setPrecision(rsmd.getPrecision(i));
            column.setScale(rsmd.getScale(i));
            if (column.getScale() == 0 && sqlType == Types.NUMERIC) {
                column.setJavaType("Long");
            }
            column.setName(StringTools.lower(StringTools.camelStyle(column.getColumnLabel())));
            columns.add(column);
        }

        resultModel.setHeaders(columns);

        if (!supportsPhysicalPage) {
            this.skipRows(rs, start);
        }

        int k = 0;
        while (rs.next() && k++ < pageSize) {
            int index = 0;
            RowModel rowModel = new RowModel();
            Iterator<ColumnDefinition> iterator = columns.iterator();
            while (iterator.hasNext()) {
                ColumnDefinition column = iterator.next();
                ColumnDefinition c = new ColumnDefinition();
                c.setColumnName(column.getColumnName());
                c.setColumnLabel(column.getColumnLabel());
                c.setName(column.getName());
                c.setJavaType(column.getJavaType());
                c.setPrecision(column.getPrecision());
                c.setScale(column.getScale());
                String javaType = column.getJavaType();
                index = index + 1;
                if ("String".equals(javaType)) {
                    String value = rs.getString(column.getIndex());
                    c.setValue(value);
                } else if ("Integer".equals(javaType)) {
                    try {
                        Integer value = rs.getInt(column.getIndex());
                        c.setValue(value);
                    } catch (Exception e) {
                        String str = rs.getString(column.getIndex());
                        str = StringTools.replace(str, "$", "");
                        str = StringTools.replace(str, "", "");
                        str = StringTools.replace(str, ",", "");
                        NumberFormat fmt = NumberFormat.getInstance();
                        Number num = fmt.parse(str);
                        c.setValue(num.intValue());
                    }
                } else if ("Long".equals(javaType)) {
                    try {
                        Long value = rs.getLong(column.getIndex());
                        c.setValue(value);
                    } catch (Exception e) {
                        String str = rs.getString(column.getIndex());
                        str = StringTools.replace(str, "$", "");
                        str = StringTools.replace(str, "", "");
                        str = StringTools.replace(str, ",", "");
                        NumberFormat fmt = NumberFormat.getInstance();
                        Number num = fmt.parse(str);
                        c.setValue(num.longValue());
                    }
                } else if ("Double".equals(javaType)) {
                    try {
                        Double value = rs.getDouble(column.getIndex());
                        c.setValue(value);
                    } catch (Exception e) {
                        String str = rs.getString(column.getIndex());
                        str = StringTools.replace(str, "$", "");
                        str = StringTools.replace(str, "", "");
                        str = StringTools.replace(str, ",", "");
                        NumberFormat fmt = NumberFormat.getInstance();
                        Number num = fmt.parse(str);
                        c.setValue(num.doubleValue());
                    }
                } else if ("Boolean".equals(javaType)) {
                    Boolean value = rs.getBoolean(column.getIndex());
                    c.setValue(value);
                } else if ("Date".equals(javaType)) {
                    Timestamp value = rs.getTimestamp(column.getIndex());
                    c.setValue(value);
                } else {
                    c.setValue(rs.getObject(column.getIndex()));
                }
                rowModel.addColumn(c);
            }
            resultModel.addRow(rowModel);
        }
    } catch (Exception ex) {
        logger.error(ex);
        ex.printStackTrace();
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(psmt);
        JdbcUtils.close(rs);
    }
    return resultModel;
}

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

@Override
public LinkedList<String> buildTable(String tableHeader, 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/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("TABLE BUILT ")
            + new Date()
            + java.util.ResourceBundle
                    .getBundle(/* w  w  w.j av a  2  s.c  o m*/
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                    .getString(" BY CANREG5.");

    String notesString = "";

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

    int[] years = { startYear, endYear };

    double casesArray[][][] = null; // a 3D array of sex, icd and agegroup - with one extra layer in all dimensions containing a sum of all
    double populationArray[][] = null; // contains population count in the following format: [sex][agegroup]

    //      double RegPop[][];
    double totalCasesPerHundredThousand[][];
    double crudeRate[][];
    double MV[][];
    double ASR[][];
    double ASRbyAgeGroup[][][];
    double ratei[][];
    //      double vASR[][];
    double ASRluL[][][];
    double variL[][];
    double variLbyAgeGroup[][][];
    double DCO[][];

    char ASRf[][];
    double ASRratio[][];
    char MVf[][];

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

    LinkedList cancerGroupsLocal[] = null;

    LinkedList<FieldDescription> incidenceFieldDescriptionList = 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/AgeSpecificCasesPerHundredThousandTableBuilder")
                .getString("FILTER USED:") + " " + populations[0].getFilter();
    }

    if (populations.length > 0) {
        notesString += ", "
                + java.util.ResourceBundle.getBundle(
                        "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                        .getString("REFERENCE POPULATION:")
                + " " + populations[0].getReferencePopulation().getPopulationDatasetName();
    }

    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

    // Generate based on death certificate only
    DCO = new double[numberOfSexes][numberOfCancerGroups];

    // and microscopical verification
    MV = new double[numberOfSexes][numberOfCancerGroups];

    String sexString;
    String icdString;
    String morphologyString;
    String yearString;
    String ageString;
    String basisString;
    String casesString;

    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")) {
                        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;
                        } else {
                            icdIndex = DONT_COUNT;
                        }
                    }

                }

                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;

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

        }
    }
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("PROCESSED ")
            + records
            + java.util.ResourceBundle
                    .getBundle(
                            "canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
                    .getString(" RECORDS."));

    // Get our matrixes ready
    // Age standarized rate
    ASR = new double[numberOfSexes][numberOfCancerGroups];
    ASRbyAgeGroup = new double[numberOfSexes][numberOfCancerGroups][numberOfAgeGroups];
    ASRluL = new double[numberOfSexes][numberOfCancerGroups][2];
    variL = new double[numberOfSexes][numberOfCancerGroups];
    variLbyAgeGroup = new double[numberOfSexes][numberOfCancerGroups][numberOfAgeGroups];

    // Total casesPerHundredThousand
    totalCasesPerHundredThousand = 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;

            totalCasesPerHundredThousand[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]));

                    ASR[sexNumber][icdGroup] += asr;

                    ASRbyAgeGroup[sexNumber][icdGroup][ageGroupNumber] = asr;

                    /* We don't use confidence intervals so this was removed 16.07.07
                    double varil =
                    calculateVariL((previousAgeGroupCases +
                    casesArray[icdGroup][sex][
                    ageGroup]),
                    (previousAgeGroupWstdPopulation +
                    wstdPop[ageGroup]),
                    (previousAgeGroupPopulation +
                    populationArray[sex][ageGroup])
                    );
                            
                    variL[sex][icdGroup] += varil;
                    variLbyAgeGroup[sex][icdGroup][ageGroup] = varil;
                     */
                    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];
                }

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

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

                ASRbyAgeGroup[sexNumber][icdGroup][highestPopulationAgeGroup] = asr;
                /* We don't use confidence intervals so this was removed 16.07.07
                double varil = calculateVariL(lastAgeGroupCases,
                lastAgeGroupWstdPopulation, lastAgeGroupPopulation);
                        
                variL[sex][icdGroup] += varil;
                        
                variLbyAgeGroup[sex][icdGroup][highestPopulationAgeGroup] =
                varil;
                 */

            }

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

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

                DCO[sexNumber][icdGroup] = 100 * (int) DCO[sexNumber][icdGroup]
                        / totalCasesPerHundredThousand[sexNumber][icdGroup];
                MV[sexNumber][icdGroup] = 100 * (int) MV[sexNumber][icdGroup]
                        / totalCasesPerHundredThousand[sexNumber][icdGroup];
                crudeRate[sexNumber][icdGroup] = totalCasesPerHundredThousand[sexNumber][icdGroup]
                        * standardPopulationArray[sexNumber][allAgeGroupsIndex]
                        / (populationArray[sexNumber][allAgeGroupsIndex]);

                /* 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;
                    }
                }

                // adjust the ASR and cum rates for unknown ages
                if (ASR[sexNumber][icdGroup] > 0) {
                    double ratio = totalCasesPerHundredThousand[sexNumber][icdGroup]
                            / (totalCasesPerHundredThousand[sexNumber][icdGroup]
                                    - casesArray[icdGroup][sexNumber][unknownAgeGroupIndex]);
                    ASR[sexNumber][icdGroup] *= ratio;
                    cumRate64[sexNumber][icdGroup] *= ratio;
                    cumRate74[sexNumber][icdGroup] *= ratio;

                }
                /*                    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];
                }
                }
                 */
            }
        }
    }

    // Get our matrixes ready
    ASRf = new char[numberOfSexes][numberOfCancerGroups];

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

    // Writing
    System.out.println(java.util.ResourceBundle
            .getBundle("canreg/client/analysis/resources/AgeSpecificCasesPerHundredThousandTableBuilder")
            .getString("WRITING DATA...\\N"));

    Writer reportFileWriter;

    if (fileType.equals(FileTypes.csv)) {
        // write tab separated stuff here
        // CSVWriter csvOut;
        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
                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)");
                //                csvOut.writeNext(line.toArray(new String[0]));
                CSVFormat format = CSVFormat.DEFAULT.withDelimiter(',')
                        .withHeader(headers.toArray(new String[0]));

                csvOut = new CSVPrinter(reportFileWriter, format);
                //                    csvOut.printRecord(headers);

                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(totalCasesPerHundredThousand[sexNumber][j], 0));
                        line.add(formatNumber(casesArray[j][sexNumber][unknownAgeGroupIndex], 0));
                        for (int age = 1; age <= highestPopulationAgeGroup; age++) {
                            if (casesPerHundredThousand[sexNumber][age][j] > 0) {
                                line.add(formatNumber(casesPerHundredThousand[sexNumber][age][j]));
                            } else {
                                line.add("0.0");
                            }
                        }
                        line.add(formatNumber(crudeRate[sexNumber][j], 2));
                        line.add(formatNumber(100 * totalCasesPerHundredThousand[sexNumber][j]
                                / totalCasesPerHundredThousand[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();
                    }
                }

                csvOut.flush();
                csvOut.close();
                generatedFiles.add(tabReportFileName);
            } catch (IOException ex) {
                Logger.getLogger(AgeSpecificCasesPerHundredThousandTableBuilder.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    } // Make PS-file
    else {
        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 (" + tableHeader + ") 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 0 sub def\n");
                fw.write("ASRfont SF\n");
                fw.write("0 496 MT (ASR) RS\n");
                fw.write("0 487 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("ASRitalicsfont SF\n");
                        } else {
                            fw.write("ASRfont SF\n");
                        }

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

                fw.write("/col col 20 sub def\n");
                fw.write("Tablefont SF\n");
                fw.write("0 496 MT (CUM) RS\n");
                fw.write("0 487 MT (0-74) RS\n");
                k = 475;
                if (cumRate74[sexNumber][allCancerGroupsIndex] > 0) {
                    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(cumRate74[sexNumber][j], 2) + ") RS\n");
                            k -= (tableFontSize);
                        }
                    }
                }

                fw.write("/col col 20 sub def\n");
                fw.write("Tablefont SF\n");
                fw.write("0 496 MT (CUM) RS\n");
                fw.write("0 487 MT (0-64) 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(cumRate64[sexNumber][j], 2) + ") RS\n");
                        k -= (tableFontSize);
                    }
                }
                /* No MVs shown
                fw.write("Tablefont SF\n");
                fw.write("/col col 20 sub def\n");
                fw.write("0 496 MT (MV) RS\n");
                fw.write("0 487 MT ((%)) RS\n");
                k = 475;
                for (int j = 0; j < numberOfCancerGroups; j++) {
                if (icdLabel[j].charAt(sex) == '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 (CA[sex][j] >= 0) {
                fw.write("0 " + k + " MT (" +
                formatNumber(MV[sex][j]) + ") RS\n");
                } else {
                fw.write("0 " + k + " MT (      -) RS\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
                                    * totalCasesPerHundredThousand[sexNumber][j]
                                    / totalCasesPerHundredThousand[sexNumber][allCancerGroupsButSkinIndex])
                                    + ") RS\n");
                        }
                        k -= (tableFontSize);
                    }
                }
                fw.write("/col col 20 sub def\n");
                fw.write("0 496 MT (CRUDE) RS\n");
                fw.write("0 487 MT (RATE) 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(crudeRate[sexNumber][j]) + ") 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(totalCasesPerHundredThousand[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 (casesPerHundredThousand[sexNumber][age][j] > 0) {
                                fw.write("0 " + k + " MT ("
                                        + formatNumber(casesPerHundredThousand[sexNumber][age][j]) + ") 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: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.// w ww . j av  a 2  s  .  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:com.gs.collections.impl.parallel.SerialParallelLazyPerformanceTest.java

private String formatSizeOf(Iterable<?> iterable) {
    return NumberFormat.getInstance().format(Iterate.sizeOf(iterable));
}

From source file:cz.tsystems.portablecheckin.MainActivity.java

private void populateTextsAndRbtn(ViewGroup theView) {
    String fieldName = "";
    DMCheckin checkinData = app.getCheckin();
    for (int i = 0; i < theView.getChildCount(); i++) {
        View v = theView.getChildAt(i);
        Class<? extends View> c = v.getClass();
        fieldName = (String) v.getTag();
        if (fieldName == null)
            continue;

        Field field = null;/* w  w  w.j av  a 2 s .co  m*/
        try {
            field = DMCheckin.class.getField(fieldName.toLowerCase(Locale.ENGLISH));
        } catch (NoSuchFieldException e) {
            Log.v(TAG, "NOT FOUND :" + fieldName.toLowerCase(Locale.ENGLISH));
            continue;
        }
        Log.v(TAG, fieldName.toLowerCase(Locale.ENGLISH));

        try {

            if (c == EditText.class || c == vinEditText.class || c == BaseEditText.class) {

                EditText editText = (EditText) v;
                editText.setText("");

                if (field.get(checkinData) == null)
                    continue;
                DecimalFormat nf = new DecimalFormat("#");
                if (field.getType() == String.class)// jnCheckin.hasNonNull(fieldName))
                    editText.setText((String) field.get(checkinData));
                else if (field.getType() == int.class)
                    editText.setText(String.valueOf(field.getInt(checkinData)));
                else if (field.getType() == short.class)
                    editText.setText(String.valueOf(field.getShort(checkinData)));
                else if (field.getType() == double.class)
                    editText.setText(nf.format(field.getDouble(checkinData)));
                else if (field.getType() == Double.class)
                    editText.setText(NumberFormat.getInstance().format((Double) field.get(checkinData)));
                else if (field.getType() == Date.class)
                    editText.setText(sdto.format((Date) field.get(checkinData)));

            } else if (c == Switch.class) {
                ((Switch) v).setChecked(field.getBoolean(checkinData));
            }

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
public void sube(byte[] datos, Usuario usuario, OutputStream out, Integer codigoInicial) {
    Date inicio = new Date();
    int idx = 5;/*from   w  w  w . j  a  v a2s .  c o  m*/
    int i = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yy");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(0);
    nf.setMinimumIntegerDigits(5);

    Transaction tx = null;
    try {
        String ejercicioId = "001-2012";
        Map<String, CentroCosto> centrosDeCosto = new HashMap<>();
        Map<String, TipoActivo> tipos = new HashMap<>();
        Query tipoActivoQuery = currentSession()
                .createQuery("select ta from TipoActivo ta " + "where ta.empresa.id = :empresaId "
                        + "and ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId "
                        + "and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId");
        log.debug("empresaId: {}", usuario.getEmpresa().getId());
        log.debug("ejercicioId: {}", ejercicioId);
        log.debug("organizacionId: {}", usuario.getEmpresa().getOrganizacion().getId());
        tipoActivoQuery.setLong("empresaId", usuario.getEmpresa().getId());
        tipoActivoQuery.setString("ejercicioId", ejercicioId);
        tipoActivoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId());
        List<TipoActivo> listaTipos = tipoActivoQuery.list();
        for (TipoActivo tipoActivo : listaTipos) {
            tipos.put(tipoActivo.getCuenta().getId().getIdCtaMayor(), tipoActivo);
        }
        log.debug("TIPOS: {}", tipos);

        Query proveedorQuery = currentSession().createQuery(
                "select p from Proveedor p where p.empresa.id = :empresaId and p.nombre = :nombreEmpresa");
        proveedorQuery.setLong("empresaId", usuario.getEmpresa().getId());
        proveedorQuery.setString("nombreEmpresa", usuario.getEmpresa().getNombre());
        Proveedor proveedor = (Proveedor) proveedorQuery.uniqueResult();

        Query codigoDuplicadoQuery = currentSession()
                .createQuery("select a from Activo a where a.empresa.id = :empresaId and a.codigo = :codigo");

        XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(datos));
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet ccostoFantasma = wb.createSheet("CCOSTO-FANTASMAS");
        int ccostoFantasmaRow = 0;
        XSSFSheet sinCCosto = wb.createSheet("SIN-CCOSTO");
        int sinCCostoRow = 0;
        XSSFSheet codigoAsignado = wb.createSheet("CODIGO-ASIGNADO");
        int codigoAsignadoRow = 0;
        XSSFSheet fechaInvalida = wb.createSheet("FECHA-INVALIDA");
        int fechaInvalidaRow = 0;
        XSSFSheet sinCosto = wb.createSheet("SIN-COSTO");
        int sinCostoRow = 0;

        tx = currentSession().beginTransaction();
        for (idx = 0; idx <= 5; idx++) {
            XSSFSheet sheet = workbook.getSheetAt(idx);

            int rows = sheet.getPhysicalNumberOfRows();
            for (i = 2; i < rows; i++) {
                log.debug("Leyendo pagina {} renglon {}", idx, i);
                XSSFRow row = sheet.getRow(i);
                if (row.getCell(0) == null) {
                    break;
                }
                String nombreGrupo = row.getCell(0).getStringCellValue().trim();
                TipoActivo tipoActivo = tipos.get(nombreGrupo);
                if (tipoActivo != null) {
                    String cuentaCCosto = row.getCell(2).toString().trim();
                    if (StringUtils.isNotBlank(cuentaCCosto)) {
                        CentroCosto centroCosto = centrosDeCosto.get(cuentaCCosto);
                        if (centroCosto == null) {
                            Query ccostoQuery = currentSession().createQuery("select cc from CentroCosto cc "
                                    + "where cc.id.ejercicio.id.idEjercicio = :ejercicioId "
                                    + "and cc.id.ejercicio.id.organizacion.id = :organizacionId "
                                    + "and cc.id.idCosto like :idCosto");
                            ccostoQuery.setString("ejercicioId", ejercicioId);
                            ccostoQuery.setLong("organizacionId",
                                    usuario.getEmpresa().getOrganizacion().getId());
                            ccostoQuery.setString("idCosto", "1.01." + cuentaCCosto);
                            ccostoQuery.setMaxResults(1);
                            List<CentroCosto> listaCCosto = ccostoQuery.list();
                            if (listaCCosto != null && listaCCosto.size() > 0) {
                                centroCosto = listaCCosto.get(0);
                            }
                            if (centroCosto == null) {
                                XSSFRow renglon = ccostoFantasma.createRow(ccostoFantasmaRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(row.getCell(8).toString());
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                continue;
                            }
                            centrosDeCosto.put(cuentaCCosto, centroCosto);
                        }
                        String poliza = null;
                        switch (row.getCell(4).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            poliza = row.getCell(4).toString();
                            poliza = StringUtils.removeEnd(poliza, ".0");
                            log.debug("POLIZA-N: {}", poliza);
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            poliza = row.getCell(4).getStringCellValue().trim();
                            log.debug("POLIZA-S: {}", poliza);
                            break;
                        }
                        Boolean seguro = false;
                        if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
                            seguro = true;
                        }
                        Boolean garantia = false;
                        if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
                            garantia = true;
                        }
                        Date fechaCompra = null;
                        if (row.getCell(7) != null) {
                            log.debug("VALIDANDO FECHA");
                            XSSFCell cell = row.getCell(7);
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                log.debug("ES NUMERIC");
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    log.debug("ES FECHA");
                                    fechaCompra = cell.getDateCellValue();
                                } else if (DateUtil.isCellInternalDateFormatted(cell)) {
                                    log.debug("ES FECHA INTERNAL");
                                    fechaCompra = cell.getDateCellValue();
                                } else {
                                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
                                    bd = stripTrailingZeros(bd);

                                    log.debug("CONVIRTIENDO DOUBLE {} - {}",
                                            DateUtil.isValidExcelDate(bd.doubleValue()), bd);
                                    fechaCompra = HSSFDateUtil.getJavaDate(bd.longValue(), true);
                                    log.debug("Cal: {}", fechaCompra);
                                }
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                log.debug("ES FORMULA");
                                CellValue cellValue = evaluator.evaluate(cell);
                                switch (cellValue.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        fechaCompra = DateUtil.getJavaDate(cellValue.getNumberValue(), true);
                                    }
                                }
                            }
                        }
                        if (row.getCell(7) != null && fechaCompra == null) {
                            String fechaCompraString;
                            if (row.getCell(7).getCellType() == Cell.CELL_TYPE_STRING) {
                                fechaCompraString = row.getCell(7).getStringCellValue();
                            } else {
                                fechaCompraString = row.getCell(7).toString().trim();
                            }
                            try {
                                fechaCompra = sdf.parse(fechaCompraString);
                            } catch (ParseException e) {
                                try {
                                    fechaCompra = sdf2.parse(fechaCompraString);
                                } catch (ParseException e2) {
                                    try {
                                        fechaCompra = sdf3.parse(fechaCompraString);
                                    } catch (ParseException e3) {
                                        // no se pudo convertir
                                    }
                                }
                            }
                        }

                        if (fechaCompra == null) {
                            XSSFRow renglon = fechaInvalida.createRow(fechaInvalidaRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        String codigo = null;
                        switch (row.getCell(8).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            codigo = row.getCell(8).toString();
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            codigo = row.getCell(8).getStringCellValue().trim();
                            break;
                        }
                        if (StringUtils.isBlank(codigo)) {
                            codigo = nf.format(codigoInicial);
                            XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(codigoInicial);
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            codigoInicial++;
                        } else {
                            // busca codigo duplicado
                            if (codigo.contains(".")) {
                                codigo = codigo.substring(0, codigo.lastIndexOf("."));
                                log.debug("CODIGO: {}", codigo);
                            }

                            codigoDuplicadoQuery.setLong("empresaId", usuario.getEmpresa().getId());
                            codigoDuplicadoQuery.setString("codigo", codigo);
                            Activo activo = (Activo) codigoDuplicadoQuery.uniqueResult();
                            if (activo != null) {
                                XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(codigo + "-" + nf.format(codigoInicial));
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                codigo = nf.format(codigoInicial);
                                codigoInicial++;
                            }
                        }
                        String descripcion = null;
                        if (row.getCell(9) != null) {
                            switch (row.getCell(9).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                descripcion = row.getCell(9).toString();
                                descripcion = StringUtils.removeEnd(descripcion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                descripcion = row.getCell(9).getStringCellValue().trim();
                                break;
                            default:
                                descripcion = row.getCell(9).toString().trim();
                            }
                        }
                        String marca = null;
                        if (row.getCell(10) != null) {
                            switch (row.getCell(10).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                marca = row.getCell(10).toString();
                                marca = StringUtils.removeEnd(marca, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                marca = row.getCell(10).getStringCellValue().trim();
                                break;
                            default:
                                marca = row.getCell(10).toString().trim();
                            }
                        }
                        String modelo = null;
                        if (row.getCell(11) != null) {
                            switch (row.getCell(11).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                modelo = row.getCell(11).toString();
                                modelo = StringUtils.removeEnd(modelo, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                modelo = row.getCell(11).getStringCellValue().trim();
                                break;
                            default:
                                modelo = row.getCell(11).toString().trim();
                            }
                        }
                        String serie = null;
                        if (row.getCell(12) != null) {
                            switch (row.getCell(12).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                serie = row.getCell(12).toString();
                                serie = StringUtils.removeEnd(serie, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                serie = row.getCell(12).getStringCellValue().trim();
                                break;
                            default:
                                serie = row.getCell(12).toString().trim();
                            }
                        }
                        String responsable = null;
                        if (row.getCell(13) != null) {
                            switch (row.getCell(13).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                responsable = row.getCell(13).toString();
                                responsable = StringUtils.removeEnd(responsable, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                responsable = row.getCell(13).getStringCellValue().trim();
                                break;
                            default:
                                responsable = row.getCell(13).toString().trim();
                            }
                        }

                        String ubicacion = null;
                        if (row.getCell(14) != null) {
                            switch (row.getCell(14).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                ubicacion = row.getCell(14).toString();
                                ubicacion = StringUtils.removeEnd(ubicacion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                ubicacion = row.getCell(14).getStringCellValue().trim();
                                break;
                            default:
                                ubicacion = row.getCell(14).toString().trim();
                            }
                        }
                        BigDecimal costo = null;
                        switch (row.getCell(15).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            costo = new BigDecimal(row.getCell(15).getNumericCellValue(), mc);
                            log.debug("COSTO-N: {} - {}", costo, row.getCell(15).getNumericCellValue());
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            costo = new BigDecimal(row.getCell(15).toString(), mc);
                            log.debug("COSTO-S: {} - {}", costo, row.getCell(15).toString());
                            break;
                        case XSSFCell.CELL_TYPE_FORMULA:
                            costo = new BigDecimal(
                                    evaluator.evaluateInCell(row.getCell(15)).getNumericCellValue(), mc);
                            log.debug("COSTO-F: {}", costo);
                        }
                        if (costo == null) {
                            XSSFRow renglon = sinCosto.createRow(sinCostoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        Activo activo = new Activo(fechaCompra, seguro, garantia, poliza, codigo, descripcion,
                                marca, modelo, serie, responsable, ubicacion, costo, tipoActivo, centroCosto,
                                proveedor, usuario.getEmpresa());
                        this.crea(activo, usuario);

                    } else {
                        XSSFRow renglon = sinCCosto.createRow(sinCCostoRow++);
                        renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                        renglon.createCell(1).setCellValue(row.getCell(0).toString());
                        renglon.createCell(2).setCellValue(row.getCell(1).toString());
                        renglon.createCell(3).setCellValue(row.getCell(2).toString());
                        renglon.createCell(4).setCellValue(row.getCell(3).toString());
                        renglon.createCell(5).setCellValue(row.getCell(4).toString());
                        renglon.createCell(6).setCellValue(row.getCell(5).toString());
                        renglon.createCell(7).setCellValue(row.getCell(6).toString());
                        renglon.createCell(8).setCellValue(row.getCell(7).toString());
                        renglon.createCell(9).setCellValue(row.getCell(8).toString());
                        renglon.createCell(10).setCellValue(row.getCell(9).toString());
                        renglon.createCell(11).setCellValue(row.getCell(10).toString());
                        renglon.createCell(12).setCellValue(row.getCell(11).toString());
                        renglon.createCell(13).setCellValue(row.getCell(12).toString());
                        renglon.createCell(14).setCellValue(row.getCell(13).toString());
                        renglon.createCell(15).setCellValue(row.getCell(14).toString());
                        renglon.createCell(16).setCellValue(row.getCell(15).toString());
                        continue;
                    }
                } else {
                    throw new RuntimeException(
                            "(" + idx + ":" + i + ") No se encontro el tipo de activo " + nombreGrupo);
                }
            }
        }
        tx.commit();
        log.debug("################################################");
        log.debug("################################################");
        log.debug("TERMINO EN {} MINS", (new Date().getTime() - inicio.getTime()) / (1000 * 60));
        log.debug("################################################");
        log.debug("################################################");

        wb.write(out);
    } catch (IOException | RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        log.error("Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
        throw new RuntimeException(
                "Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
    }
}

From source file:com.autentia.intra.bean.billing.BillBean.java

public String getNumberDefault() {
    if (getNumber() == null) {
        int maximo = 0;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(2);//from  w  w  w .j ava 2  s .c o m
        String regex = "F\\d+/";
        String anio = nf.format(new Date().getYear() - 100);
        regex = regex.concat(anio);
        BillSearch billSearch = new BillSearch();
        billSearch.setBillType(BillType.ISSUED);
        List<Bill> list = billDAO.search(billSearch, null);
        for (Bill o : list) {
            String number = o.getNumber();
            if (number != null && number.matches(regex)) {
                int x = Integer.parseInt(number.substring(1, number.indexOf('/')));
                if (x > maximo)
                    maximo = x;
            }
        }
        nf.setMinimumIntegerDigits(3);
        return "F".concat(nf.format(maximo + 1)).concat("/").concat(anio);
    } else {
        return getNumber();
    }
}

From source file:AppearanceExplorer.java

public void init() {

    // initialize the code base
    try {/*from  w w  w .j  av  a  2  s. co m*/
        java.net.URL codeBase = getCodeBase();
        codeBaseString = codeBase.toString();
    } catch (Exception e) {
        // probably running as an application, try the application
        // code base
        codeBaseString = "file:./";
    }

    // set up a NumFormat object to print out float with only 3 fraction
    // digits
    nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();

    canvas = new Canvas3D(config);
    canvas.setSize(600, 600);

    u = new SimpleUniverse(canvas);

    if (isApplication) {
        offScreenCanvas = new OffScreenCanvas3D(config, true);
        // set the size of the off-screen canvas based on a scale
        // of the on-screen size
        Screen3D sOn = canvas.getScreen3D();
        Screen3D sOff = offScreenCanvas.getScreen3D();
        Dimension dim = sOn.getSize();
        dim.width *= offScreenScale;
        dim.height *= offScreenScale;
        sOff.setSize(dim);
        sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth() * offScreenScale);
        sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight() * offScreenScale);

        // attach the offscreen canvas to the view
        u.getViewer().getView().addCanvas3D(offScreenCanvas);
    }
    contentPane.add("Center", canvas);

    BackgroundTool bgTool = new BackgroundTool(codeBaseString);
    bgSwitch = bgTool.getSwitch();
    bgChooser = bgTool.getChooser();

    // Create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();

    // set up sound
    u.getViewer().createAudioDevice();

    // get the view
    view = u.getViewer().getView();

    // Get the viewing platform
    ViewingPlatform viewingPlatform = u.getViewingPlatform();

    // Move the viewing platform back to enclose the -2 -> 2 range
    double viewRadius = 2.0; // want to be able to see circle
    // of viewRadius size around origin
    // get the field of view
    double fov = u.getViewer().getView().getFieldOfView();

    // calc view distance to make circle view in fov
    float viewDistance = (float) (viewRadius / Math.tan(fov / 2.0));
    tmpVector.set(0.0f, 0.0f, viewDistance);// setup offset
    tmpTrans.set(tmpVector); // set trans to translate
    // move the view platform
    viewingPlatform.getViewPlatformTransform().setTransform(tmpTrans);

    // add an orbit behavior to move the viewing platform
    OrbitBehavior orbit = new OrbitBehavior(canvas,
            OrbitBehavior.PROPORTIONAL_ZOOM | OrbitBehavior.REVERSE_ROTATE | OrbitBehavior.REVERSE_TRANSLATE);
    orbit.setZoomFactor(0.25);
    BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    orbit.setSchedulingBounds(bounds);
    viewingPlatform.setViewPlatformBehavior(orbit);

    u.addBranchGraph(scene);

    contentPane.add("East", guiPanel());
}

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);/*www .java  2 s  .  co 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.autentia.intra.bean.contacts.OfferBean.java

public String getNumberDefault() {
    if (getNumber() == null) {
        int maximo = 0;
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumIntegerDigits(2);/*from   w  ww.  java  2s  .  c  om*/
        String regex = "P\\d+/";
        String anio = nf.format(new Date().getYear() - 100);
        regex = regex.concat(anio);
        List<Offer> list = offerDAO.search(null);
        for (Offer o : list) {
            String number = o.getNumber();
            if (number != null && number.matches(regex)) {
                int x = Integer.parseInt(number.substring(1, number.indexOf('/')));
                if (x > maximo)
                    maximo = x;
            }
        }
        nf.setMinimumIntegerDigits(3);
        return "P".concat(nf.format(maximo + 1)).concat("/").concat(anio);
    } else {
        return getNumber();
    }
}