Example usage for org.apache.commons.lang3 StringUtils leftPad

List of usage examples for org.apache.commons.lang3 StringUtils leftPad

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils leftPad.

Prototype

public static String leftPad(final String str, final int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Pad to a size of size .

 StringUtils.leftPad(null, *, *)      = null StringUtils.leftPad("", 3, "z")      = "zzz" StringUtils.leftPad("bat", 3, "yz")  = "bat" StringUtils.leftPad("bat", 5, "yz")  = "yzbat" StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat" StringUtils.leftPad("bat", 1, "yz")  = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null)  = "  bat" StringUtils.leftPad("bat", 5, "")    = "  bat" 

Usage

From source file:org.voltdb.utils.CatalogSchemaTools.java

/**
 * Convert a Table catalog object into the proper SQL DDL, including all indexes,
 * constraints, and foreign key references.
 * Also returns just the CREATE TABLE statement, since, like all good methods,
 * it should have two purposes....//from  w  ww  .  j a  v  a2s . co  m
 * It would be nice to have a separate method to just generate the CREATE TABLE,
 * but we use that pass to also figure out what separate constraint and index
 * SQL DDL needs to be generated, so instead, we opt to build the CREATE TABLE DDL
 * separately as we go here, and then fill it in to the StringBuilder being used
 * to construct the full canonical DDL at the appropriate time.
 * @param Table - object to be analyzed
 * @param String - the Query if this Table is a View
 * @param Boolean - true if this Table is an Export Table
 * @return SQL Schema text representing the CREATE TABLE statement to generate the table
 */
public static String toSchema(StringBuilder sb, Table catalog_tbl, String viewQuery,
        String isExportTableWithTarget) {
    assert (!catalog_tbl.getColumns().isEmpty());
    boolean tableIsView = (viewQuery != null);

    // We need the intermediate results of building the table schema string so that
    // we can return the full CREATE TABLE statement, so accumulate it separately
    StringBuilder table_sb = new StringBuilder();

    Set<Index> skip_indexes = new HashSet<Index>();
    Set<Constraint> skip_constraints = new HashSet<Constraint>();

    if (tableIsView) {
        table_sb.append("CREATE VIEW " + catalog_tbl.getTypeName() + " (");
    } else {
        table_sb.append("CREATE TABLE " + catalog_tbl.getTypeName() + " (");
    }

    // Columns
    String add = "\n";
    for (Column catalog_col : CatalogUtil.getSortedCatalogItems(catalog_tbl.getColumns(), "index")) {
        VoltType col_type = VoltType.get((byte) catalog_col.getType());

        // this next assert would be great if we dealt with default values well
        //assert(! ((catalog_col.getDefaultvalue() == null) && (catalog_col.getNullable() == false) ) );

        if (tableIsView) {
            table_sb.append(add + spacer + catalog_col.getTypeName());
            add = ",\n";
            continue;
        }

        table_sb.append(add + spacer + catalog_col.getTypeName() + " " + col_type.toSQLString()
                + ((col_type == VoltType.STRING || col_type == VoltType.VARBINARY) && catalog_col.getSize() > 0
                        ? "(" + catalog_col.getSize() + (catalog_col.getInbytes() ? " BYTES" : "") + ")"
                        : ""));

        // Default value
        String defaultvalue = catalog_col.getDefaultvalue();
        //VoltType defaulttype = VoltType.get((byte)catalog_col.getDefaulttype());
        boolean nullable = catalog_col.getNullable();
        // TODO: Shouldn't have to check whether the string contains "null"
        if (defaultvalue == null) {
        } else if (defaultvalue.toLowerCase().equals("null") && nullable) {
            defaultvalue = null;
        } else {
            if (col_type == VoltType.TIMESTAMP) {
                if (defaultvalue.startsWith("CURRENT_TIMESTAMP")) {
                    defaultvalue = "CURRENT_TIMESTAMP";
                } else {
                    assert (defaultvalue.matches("[0-9]+"));
                    long epoch = Long.parseLong(defaultvalue);
                    Date d = new Date(epoch / 1000);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    defaultvalue = "\'" + sdf.format(d) + "."
                            + StringUtils.leftPad(String.valueOf(epoch % 1000000), 6, "0") + "\'";
                }
            } else {
                // XXX: if (defaulttype != VoltType.VOLTFUNCTION) {
                // TODO: Escape strings properly
                defaultvalue = defaultvalue.replace("\'", "\'\'");
                defaultvalue = "'" + defaultvalue + "'";
            }
        }
        if (defaultvalue == null) {
            table_sb.append((!nullable ? " NOT NULL" : ""));
        } else {
            table_sb.append(" DEFAULT " + (defaultvalue != null ? defaultvalue : "NULL")
                    + (!nullable ? " NOT NULL" : ""));
        }

        // Single-column constraints
        for (ConstraintRef catalog_const_ref : catalog_col.getConstraints()) {
            Constraint catalog_const = catalog_const_ref.getConstraint();
            ConstraintType const_type = ConstraintType.get(catalog_const.getType());

            // Check if there is another column in our table with the same constraint
            // If there is, then we need to add it to the end of the table definition
            boolean found = false;
            for (Column catalog_other_col : catalog_tbl.getColumns()) {
                if (catalog_other_col.equals(catalog_col))
                    continue;
                if (catalog_other_col.getConstraints().getIgnoreCase(catalog_const.getTypeName()) != null) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                switch (const_type) {
                case FOREIGN_KEY: {
                    Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
                    Column catalog_fkey_col = null;
                    for (ColumnRef ref : catalog_const.getForeignkeycols()) {
                        catalog_fkey_col = ref.getColumn();
                        break; // Nasty hack to get first item
                    }

                    assert (catalog_fkey_col != null);
                    table_sb.append(" REFERENCES " + catalog_fkey_tbl.getTypeName() + " ("
                            + catalog_fkey_col.getTypeName() + ")");
                    skip_constraints.add(catalog_const);
                    break;
                }
                default:
                    // Nothing for now
                }
            }
        }

        add = ",\n";
    }

    // Constraints
    for (Constraint catalog_const : catalog_tbl.getConstraints()) {
        if (skip_constraints.contains(catalog_const))
            continue;
        ConstraintType const_type = ConstraintType.get(catalog_const.getType());

        // Primary Keys / Unique Constraints
        if (const_type == ConstraintType.PRIMARY_KEY || const_type == ConstraintType.UNIQUE) {
            Index catalog_idx = catalog_const.getIndex();
            if (!tableIsView) {
                // Get the ConstraintType.

                table_sb.append(add + spacer);
                if (!catalog_const.getTypeName().startsWith(HSQLInterface.AUTO_GEN_PREFIX)) {
                    table_sb.append("CONSTRAINT " + catalog_const.getTypeName() + " ");
                }
                if (const_type == ConstraintType.PRIMARY_KEY || const_type == ConstraintType.UNIQUE) {
                    if (const_type == ConstraintType.PRIMARY_KEY) {
                        table_sb.append("PRIMARY KEY (");
                    } else {
                        if (catalog_idx.getAssumeunique()) {
                            table_sb.append("ASSUMEUNIQUE (");
                        } else {
                            table_sb.append("UNIQUE (");
                        }
                    }
                    String col_add = "";
                    String exprStrings = new String();
                    if (catalog_idx.getExpressionsjson() != null
                            && !catalog_idx.getExpressionsjson().equals("")) {
                        StmtTargetTableScan tableScan = new StmtTargetTableScan(catalog_tbl,
                                catalog_tbl.getTypeName());
                        try {
                            List<AbstractExpression> expressions = AbstractExpression
                                    .fromJSONArrayString(catalog_idx.getExpressionsjson(), tableScan);
                            String sep = "";
                            for (AbstractExpression expr : expressions) {
                                exprStrings += sep + expr.explain(catalog_tbl.getTypeName());
                                sep = ",";
                            }
                        } catch (JSONException e) {
                        }
                        table_sb.append(col_add + exprStrings);
                    } else {
                        for (ColumnRef catalog_colref : CatalogUtil
                                .getSortedCatalogItems(catalog_idx.getColumns(), "index")) {
                            table_sb.append(col_add + catalog_colref.getColumn().getTypeName());
                            col_add = ", ";
                        } // FOR
                    }
                    table_sb.append(")");
                }
            }
            if (catalog_idx.getTypeName().startsWith(HSQLInterface.AUTO_GEN_PREFIX)
                    || catalog_idx.getTypeName().startsWith(HSQLInterface.AUTO_GEN_MATVIEW)) {
                skip_indexes.add(catalog_idx);
            }

            // Foreign Key
        } else if (const_type == ConstraintType.FOREIGN_KEY) {
            Table catalog_fkey_tbl = catalog_const.getForeignkeytable();
            String col_add = "";
            String our_columns = "";
            String fkey_columns = "";
            for (ColumnRef catalog_colref : catalog_const.getForeignkeycols()) {
                // The name of the ColumnRef is the column in our base table
                Column our_column = catalog_tbl.getColumns().getIgnoreCase(catalog_colref.getTypeName());
                assert (our_column != null);
                our_columns += col_add + our_column.getTypeName();

                Column fkey_column = catalog_colref.getColumn();
                assert (fkey_column != null);
                fkey_columns += col_add + fkey_column.getTypeName();

                col_add = ", ";
            }
            table_sb.append(add + spacer + "CONSTRAINT " + catalog_const.getTypeName() + " " + "FOREIGN KEY ("
                    + our_columns + ") " + "REFERENCES " + catalog_fkey_tbl.getTypeName() + " (" + fkey_columns
                    + ")");
        }
        skip_constraints.add(catalog_const);
    }

    if (catalog_tbl.getTuplelimit() != Integer.MAX_VALUE) {
        table_sb.append(add + spacer + "LIMIT PARTITION ROWS " + String.valueOf(catalog_tbl.getTuplelimit()));
        String deleteStmt = CatalogUtil.getLimitPartitionRowsDeleteStmt(catalog_tbl);
        if (deleteStmt != null) {
            if (deleteStmt.endsWith(";")) {
                // StatementCompiler appends the semicolon, we don't want it here.
                deleteStmt = deleteStmt.substring(0, deleteStmt.length() - 1);
            }
            table_sb.append(" EXECUTE (" + deleteStmt + ")");
        }
    }

    if (viewQuery != null) {
        table_sb.append("\n) AS \n");
        table_sb.append(spacer + viewQuery + ";\n");
    } else {
        table_sb.append("\n);\n");
    }

    // We've built the full CREATE TABLE statement for this table,
    // Append the generated table schema to the canonical DDL StringBuilder
    sb.append(table_sb.toString());

    // Partition Table
    if (catalog_tbl.getPartitioncolumn() != null && viewQuery == null) {
        sb.append("PARTITION TABLE " + catalog_tbl.getTypeName() + " ON COLUMN "
                + catalog_tbl.getPartitioncolumn().getTypeName() + ";\n");
    }

    // All other Indexes
    for (Index catalog_idx : catalog_tbl.getIndexes()) {
        if (skip_indexes.contains(catalog_idx))
            continue;

        if (catalog_idx.getUnique()) {
            if (catalog_idx.getAssumeunique()) {
                sb.append("CREATE ASSUMEUNIQUE INDEX ");
            } else {
                sb.append("CREATE UNIQUE INDEX ");
            }
        } else {
            sb.append("CREATE INDEX ");
        }

        sb.append(catalog_idx.getTypeName() + " ON " + catalog_tbl.getTypeName() + " (");
        add = "";

        String jsonstring = catalog_idx.getExpressionsjson();

        if (jsonstring.isEmpty()) {
            for (ColumnRef catalog_colref : CatalogUtil.getSortedCatalogItems(catalog_idx.getColumns(),
                    "index")) {
                sb.append(add + catalog_colref.getColumn().getTypeName());
                add = ", ";
            }
        } else {
            List<AbstractExpression> indexedExprs = null;
            try {
                indexedExprs = AbstractExpression.fromJSONArrayString(jsonstring,
                        new StmtTargetTableScan(catalog_tbl, catalog_tbl.getTypeName()));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for (AbstractExpression expr : indexedExprs) {
                sb.append(add + expr.explain(catalog_tbl.getTypeName()));
                add = ", ";
            }
        }
        sb.append(")");

        String jsonPredicate = catalog_idx.getPredicatejson();
        if (!jsonPredicate.isEmpty()) {
            try {
                AbstractExpression predicate = AbstractExpression.fromJSONString(jsonPredicate,
                        new StmtTargetTableScan(catalog_tbl, catalog_tbl.getTypeName()));
                sb.append(" WHERE " + predicate.explain(catalog_tbl.getTypeName()));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        sb.append(";\n");
    }
    if (isExportTableWithTarget != null) {
        sb.append("EXPORT TABLE " + catalog_tbl.getTypeName());
        if (!isExportTableWithTarget.equalsIgnoreCase(Constants.DEFAULT_EXPORT_CONNECTOR_NAME)) {
            sb.append(" TO STREAM " + isExportTableWithTarget);
        }
        sb.append(";\n");
    }

    if (catalog_tbl.getIsdred()) {
        sb.append("DR TABLE " + catalog_tbl.getTypeName() + ";\n");
    }

    sb.append("\n");
    // Canonical DDL generation for this table is done, now just hand the CREATE TABLE
    // statement to whoever might be interested (DDLCompiler, I'm looking in your direction)
    return table_sb.toString();
}

From source file:pl.edu.icm.comac.vis.server.service.DetailsService.java

private List<Object> authorList(String id) throws OpenRDFException {
    log.debug("Preparing author list for {}", id);
    String sparqlQuery = "select ?property ?value WHERE "
            + "{ ?id <http://purl.org/ontology/bibo/authorList> ?l ." + " ?l ?property ?value }";
    RepositoryConnection conn = repo.getConnection();
    TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, sparqlQuery);
    ValueFactory valueFactory = conn.getValueFactory();
    query.setBinding("id", valueFactory.createURI(id));
    TupleQueryResult qres = query.evaluate();
    Map<String, String> orderMap = new HashMap<>();
    while (qres.hasNext()) {
        BindingSet bs = qres.next();/*from   www. j  a v a2 s  .c  o  m*/
        String prop = bs.getValue("property").stringValue();
        if (!prop.matches("http://www.w3.org/1999/02/22-rdf-syntax-ns#_\\d+")) {
            continue;
        }
        String val = bs.getValue("value").stringValue();
        String p = prop.substring("http://www.w3.org/1999/02/22-rdf-syntax-ns#_".length());
        p = StringUtils.leftPad(p, 5, '0');
        orderMap.put(p, val);
    }
    log.debug("Got {} authors", orderMap.size());
    List<Object> res = new ArrayList<>();
    for (String key : orderMap.keySet().stream().sorted().collect(Collectors.toList())) {
        final Map<String, Object> aprops = basicObjectProperties(orderMap.get(key), false);
        appendCoreProperties(aprops, orderMap.get(key));
        updateNameProperty(aprops);
        res.add(aprops);
    }
    return res;
}

From source file:playground.michalm.berlin.BerlinZoneUtils.java

public static Id<Zone> createZoneId(String id) {
    String _8digitZoneId = StringUtils.leftPad(id, 8, '0');//some ids lack leading 0's
    return Id.create(_8digitZoneId, Zone.class);
}

From source file:playground.michalm.chargerlocation.RunChargerLocationOptimization.java

private void readPotentials(Map<Id<Zone>, Zone> zones, String potentialFile, TimeHorizon horizon) {
    if (horizon == TimeHorizon._24H) {
        //TODO does not work for 24h: should be Mon 4am till Fri 4am
        throw new IllegalArgumentException();
    }/* ww w  .ja  va 2s. c om*/

    //from: 20140407000000
    //to: 20140413230000 (incl.)
    final int FROM_DAY = 1;//monday
    final int TO_DAY = 4;//thursday (incl.)

    try (Scanner s = new Scanner(new File(potentialFile))) {
        while (s.hasNext()) {
            String zoneId = StringUtils.leftPad(s.next(), 8, '0');
            Id<Zone> id = Id.create(zoneId, Zone.class);
            if (!zones.containsKey(id)) {
                s.nextLine();
                continue;
            }

            double potential = 0;
            for (int d = 1; d <= 7; d++) {
                for (int h = 1; h <= 24; h++) {
                    double p = s.nextDouble();
                    if (FROM_DAY <= d && d <= TO_DAY && horizon.fromHour <= h && h <= horizon.toHour) {
                        potential += p;
                    }
                }
            }

            zonePotentials.put(id, potential);
            totalPotential += potential;
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException();
    }
}

From source file:playground.michalm.chargerlocation.TaxiBerlin.TaxiBerlinChargerLocationOptimization.java

private DemandData<Zone> createDemandData(Map<Id<Zone>, Zone> zones, String potentialFile) {
    Map<Id<Zone>, Double> zonePotentials = new HashMap<>();

    //from: 20140407000000
    //to: 20140413230000 (incl.)
    final int FROM_DAY = 1;//monday
    final int TO_DAY = 4;//thursday (incl.)
    final int FROM_HOUR = 7;
    final int TO_HOUR = 19;//inclusive

    try (Scanner s = new Scanner(IOUtils.getBufferedReader(potentialFile))) {
        while (s.hasNext()) {
            String zoneId = StringUtils.leftPad(s.next(), 8, '0');
            Id<Zone> id = Id.create(zoneId, Zone.class);
            if (!zones.containsKey(id)) {
                s.nextLine();/*from   ww w . j  a v a 2  s  .c om*/
                continue;
            }

            double potential = 0;
            for (int d = 1; d <= 7; d++) {
                for (int h = 1; h <= 24; h++) {
                    double p = s.nextDouble();
                    if (FROM_DAY <= d && d <= TO_DAY && FROM_HOUR <= h && h <= TO_HOUR) {
                        potential += p;
                    }
                }
            }

            zonePotentials.put(id, potential);
        }
    }

    return new DemandData<Zone>(zones.values(), zonePotentials);
}

From source file:pt.ua.dicoogle.sdk.utils.TagValue.java

public String getTagID() {
    return StringUtils.leftPad(Integer.toHexString(tag), 8, '0');
}

From source file:pt.ua.dicoogle.sdk.utils.TagValue.java

public static String getGroup(int tag) {
    String result = Integer.toHexString((tag & 0xFFFF0000) >> 16);
    return StringUtils.leftPad(result, 4, '0');
}

From source file:pt.ua.dicoogle.sdk.utils.TagValue.java

public static String getSubgroup(int tag) {
    String result = Integer.toHexString(tag & 0x0000FFFF);
    return StringUtils.leftPad(result, 4, '0');
}

From source file:rems.Global.java

public static void exprtToHTMLTblr(ResultSet dtst, String fileNm, String rptTitle, String[] colsToGrp,
        String[] colsToCnt, String[] colsToSum, String[] colsToAvrg, String[] colsToFrmt, boolean isfirst,
        boolean islast, boolean shdAppnd) {
    try {//  ww  w . ja  v a  2  s.com
        System.out.println(fileNm);
        DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
        DecimalFormat myFormatter2 = new DecimalFormat("###,##0");
        dtst.last();
        int totlRows = dtst.getRow();
        dtst.beforeFirst();
        ResultSetMetaData dtstmd = dtst.getMetaData();
        int colCnt = dtstmd.getColumnCount();
        long totlLen = 0;
        for (int d = 0; d < colCnt; d++) {
            totlLen += dtstmd.getColumnName(d + 1).length();
        }
        long[] colcntVals = new long[colCnt];
        double[] colsumVals = new double[colCnt];
        double[] colavrgVals = new double[colCnt];
        String cption = "";
        if (isfirst) {
            cption = "<caption align=\"top\">" + rptTitle + "</caption>";
            Global.strSB.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
                    + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"[]><html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en-US\" xml:lang=\"en\"><head><meta http-equiv=\"Content-Type\" "
                    + "content=\"text/html; charset=utf-8\">" + System.getProperty("line.separator") + "<title>"
                    + rptTitle + "</title>" + System.getProperty("line.separator")
                    + "<link rel=\"stylesheet\" href=\"../amcharts/rpt.css\" type=\"text/css\"></head><body>");

            Files.copy(
                    new File(Global.getOrgImgsDrctry() + "/" + String.valueOf(Global.UsrsOrg_ID) + ".png")
                            .toPath(),
                    new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                            + String.valueOf(Global.UsrsOrg_ID) + ".png").toPath(),
                    StandardCopyOption.REPLACE_EXISTING);

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/images/" + String.valueOf(Global.UsrsOrg_ID) + ".png");
            }
            //Org Name
            String orgNm = Global.getOrgName(Global.UsrsOrg_ID);
            String pstl = Global.getOrgPstlAddrs(Global.UsrsOrg_ID);
            //Contacts Nos
            String cntcts = Global.getOrgContactNos(Global.UsrsOrg_ID);
            //Email Address
            String email = Global.getOrgEmailAddrs(Global.UsrsOrg_ID);

            Global.strSB
                    .append("<p><img src=\"../images/" + String.valueOf(Global.UsrsOrg_ID) + ".png\">" + orgNm
                            + "<br/>" + pstl + "<br/>" + cntcts + "<br/>" + email + "<br/>" + "</p>")
                    .append(System.getProperty("line.separator"));
        }

        Global.strSB.append("<table style=\"margin-top:5px;\">" + cption + "<thead>")
                .append(System.getProperty("line.separator"));

        int wdth = 0;
        String finalStr = " ";
        for (int d = 0; d < colCnt; d++) {
            String algn = "left";
            int colLen = dtstmd.getColumnName(d + 1).length();
            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
            if (colLen >= 3) {
                if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                    algn = "right";
                    finalStr = StringUtils.leftPad(dtstmd.getColumnName(d + 1).trim(), colLen, ' ');
                } else {
                    finalStr = dtstmd.getColumnName(d + 1).trim() + " ";
                }
                Global.strSB
                        .append("<th align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                + finalStr.replace(" ", "&nbsp;") + "</th>")
                        .append(System.getProperty("line.separator"));
            }
        }

        Global.strSB.append("</thead><tbody>").append(System.getProperty("line.separator"));

        String[][] prevRowVal = new String[totlRows][colCnt];
        dtst.beforeFirst();
        System.out.println(Global.strSB.toString());
        for (int a = 0; a < totlRows; a++) {
            dtst.next();
            Global.strSB.append("<tr>").append(System.getProperty("line.separator"));
            for (int d = 0; d < colCnt; d++) {
                String algn = "left";
                double nwval = 0;
                boolean mstgrp = Global.mustColBeGrpd(String.valueOf(d), colsToGrp);
                if (Global.mustColBeCntd(String.valueOf(d), colsToCnt) == true) {
                    if ((a > 0) && (mstgrp == true)) {
                        if ((prevRowVal[a - 1][d].equals(dtst.getString(d + 1)))) {

                        } else {
                            colcntVals[d] += 1;
                        }
                    } else {
                        colcntVals[d] += 1;
                    }
                } else if (Global.mustColBeSumd(String.valueOf(d), colsToSum) == true) {
                    nwval = Double.parseDouble(dtst.getString(d + 1));
                    if ((a > 0) && (mstgrp == true)) {
                        if ((prevRowVal[a - 1][d].equals(dtst.getString(d + 1)))) {

                        } else {
                            colsumVals[d] += nwval;
                        }
                    } else {
                        colsumVals[d] += nwval;
                    }
                } else if (Global.mustColBeAvrgd(String.valueOf(d), colsToAvrg) == true) {
                    nwval = Double.parseDouble(dtst.getString(d + 1));
                    if ((a > 0) && (mstgrp == true)) {
                        if (prevRowVal[a - 1][d].equals(dtst.getString(d + 1))) {

                        } else {
                            colcntVals[d] += 1;
                            colsumVals[d] += nwval;
                        }
                    } else {
                        colcntVals[d] += 1;
                        colsumVals[d] += nwval;
                    }
                }

                int colLen = dtstmd.getColumnName(d + 1).length();
                if (colLen >= 3) {
                    if ((a > 0) && (Global.mustColBeGrpd(String.valueOf(d), colsToGrp) == true)) {
                        if (prevRowVal[a - 1][d].equals(dtst.getString(d + 1))) {
                            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                            Global.strSB
                                    .append("<td align=\"" + algn + "\"  width=\"" + wdth + "%\">"
                                            + " ".replace(" ", "&nbsp;") + "</td>")
                                    .append(System.getProperty("line.separator"));
                        } else {
                            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                            String frsh = " ";
                            if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                                algn = "right";
                                double num = Double.parseDouble(dtst.getString(d + 1).trim());
                                if (!dtst.getString(d + 1).equals("")) {
                                    frsh = myFormatter.format(num);//.Trim().PadRight(60, ' ')
                                } else {
                                    frsh = dtst.getString(d + 1) + " ";
                                }
                            } else {
                                frsh = dtst.getString(d + 1) + " ";
                            }
                            Global.strSB.append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                    + Global.breakTxtDownHTML(frsh, dtstmd.getColumnName(d + 1).length())
                                            .replace(" ", "&nbsp;")
                                    + "</td>").append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
                        }
                    } else {
                        wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                        String frsh = " ";
                        if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                            algn = "right";
                            double num = Double.parseDouble(dtst.getString(d + 1).trim());
                            if (!dtst.getString(d + 1).equals("")) {
                                frsh = myFormatter.format(num);//.Trim().PadRight(60, ' ')
                            } else {
                                frsh = dtst.getString(d + 1) + " ";
                            }
                        } else {
                            frsh = dtst.getString(d + 1) + " ";
                        }
                        Global.strSB
                                .append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                        + Global.breakTxtDownHTML(frsh, dtstmd.getColumnName(d + 1).length())
                                                .replace(" ", "&nbsp;")
                                        + "</td>")
                                .append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
                    }
                }
            }
            Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
        }
        //Populate Counts/Sums/Averages
        Global.strSB.append("<tr>").append(System.getProperty("line.separator"));

        for (int f = 0; f < colCnt; f++) {
            String algn = "left";
            int colLen = dtstmd.getColumnName(f + 1).length();
            finalStr = " ";
            if (colLen >= 3) {
                if (Global.mustColBeCntd(String.valueOf(f), colsToCnt) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Count = " + myFormatter2.format(colcntVals[f]));
                    } else {
                        finalStr = ("Count = " + String.valueOf(colcntVals[f]));
                    }
                } else if (Global.mustColBeSumd(String.valueOf(f), colsToSum) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Sum = " + myFormatter.format(colsumVals[f]));
                    } else {
                        finalStr = ("Sum = " + String.valueOf(colcntVals[f]));
                    }
                } else if (Global.mustColBeAvrgd(String.valueOf(f), colsToAvrg) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Average = " + myFormatter.format(colsumVals[f] / colcntVals[f]));
                    } else {
                        finalStr = ("Average = " + String.valueOf(colsumVals[f] / colcntVals[f]));
                    }
                } else {
                    finalStr = " ";
                }
                Global.strSB
                        .append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                + Global.breakTxtDownHTML(finalStr, dtstmd.getColumnName(f + 1).length())
                                        .replace(" ", "&nbsp;")
                                + "</td>")
                        .append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
            }
        }
        Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
        Global.strSB.append("</tbody></table>").append(System.getProperty("line.separator"));
        if (islast) {
            Global.strSB.append("</body></html>");

            File file = new File(fileNm);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(Global.strSB.toString());
            bw.close();

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/samples/" + String.valueOf(Global.runID) + ".html");
            }
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n\r\n");
        Global.errorLog += ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n\r\n";
        Global.writeToLog();
    }
}

From source file:rems.Program.java

public static String formatDtSt(ResultSet dtst, String rptTitle, String[] colsToGrp, String[] colsToCnt,
        String[] colsToSum, String[] colsToAvrg, String[] colsToFrmt) {
    try {/*from  ww  w  .  java 2 s  .  c  om*/
        DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
        DecimalFormat myFormatter2 = new DecimalFormat("###,##0");
        String finalStr = rptTitle.toUpperCase();
        finalStr += "\r\n\r\n";
        ResultSetMetaData dtstmd = dtst.getMetaData();
        dtst.last();
        int ttlRws = dtst.getRow();
        dtst.beforeFirst();
        int colCnt = dtstmd.getColumnCount();

        long[] colcntVals = new long[colCnt];
        double[] colsumVals = new double[colCnt];
        double[] colavrgVals = new double[colCnt];
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("=", colLen, '=');
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int e = 0; e < colCnt; e++) {
            int colLen = dtstmd.getColumnName(e + 1).length();
            if (colLen >= 3) {
                if (Program.mustColBeFrmtd(String.valueOf(e), colsToFrmt) == true) {
                    finalStr += StringUtils.leftPad(dtstmd.getColumnName(e + 1).substring(0, colLen - 2).trim(),
                            colLen, ' ');
                } else {
                    finalStr += StringUtils.leftPad(dtstmd.getColumnName(e + 1).substring(0, colLen - 2),
                            colLen, ' ');
                }
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("=", colLen, '=');
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        String[][] prevRowVal = new String[ttlRws][colCnt];
        for (int i = 0; i < ttlRws; i++) {
            String[][] lineFormat = new String[colCnt][];
            dtst.next();
            for (int a = 0; a < colCnt; a++) {
                double nwval = 0;
                prevRowVal[i][a] = dtst.getString(a + 1);

                boolean mstgrp = mustColBeGrpd(String.valueOf(a), colsToGrp);
                if (mustColBeCntd(String.valueOf(a), colsToCnt) == true) {
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1))) && (mstgrp == true)) {
                    } else {
                        colcntVals[a] += 1;
                    }
                } else if (mustColBeSumd(String.valueOf(a), colsToSum) == true) {
                    nwval = Double.parseDouble(dtst.getString(a + 1));
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1))) && (mstgrp == true)) {
                    } else {
                        colsumVals[a] += nwval;
                    }
                } else if (mustColBeAvrgd(String.valueOf(a), colsToAvrg) == true) {
                    nwval = Double.parseDouble(dtst.getString(a + 1));
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1))) && (mstgrp == true)) {
                    } else {
                        colcntVals[a] += 1;
                        colsumVals[a] += nwval;
                    }
                }

                int colLen = dtstmd.getColumnName(a + 1).length();
                String[] arry;
                BufferedImage bi;
                Graphics g; // stands for Buffered Image Graphics
                Toolkit toolkit;
                MediaTracker tracker;
                if (colLen >= 3) {
                    if ((i > 0) && (prevRowVal[i - 1][a].equals(dtst.getString(a + 1)))
                            && (mustColBeGrpd(String.valueOf(a), colsToGrp) == true)) {
                        toolkit = Toolkit.getDefaultToolkit();
                        Image img = toolkit.getImage(Global.appStatPath + "/staffs.png");
                        Font nwFont = new Font("Courier New", 11, Font.PLAIN);
                        bi = new BufferedImage(70, 70, BufferedImage.TYPE_INT_RGB);
                        g = bi.getGraphics();
                        float ght = (float) g.getFontMetrics(nwFont).stringWidth(
                                StringUtils.rightPad(dtstmd.getColumnName(a + 1).trim(), colLen, '='));
                        float ght1 = (float) g.getFontMetrics(nwFont).stringWidth("=");
                        arry = breakDownStr("    ", colLen, 25, g, ght - ght1);
                    } else {
                        toolkit = Toolkit.getDefaultToolkit();
                        Image img = toolkit.getImage(Global.appStatPath + "/staffs.png");
                        Font nwFont = new Font("Courier New", 11, Font.PLAIN);
                        bi = new BufferedImage(70, 70, BufferedImage.TYPE_INT_RGB);
                        g = bi.getGraphics();
                        float ght = (float) g.getFontMetrics(nwFont).stringWidth(
                                StringUtils.rightPad(dtstmd.getColumnName(a + 1).trim(), colLen, '='));
                        float ght1 = (float) g.getFontMetrics(nwFont).stringWidth("=");
                        arry = breakDownStr(dtst.getString(a + 1), colLen, 25, g, ght - ght1);
                    }
                    lineFormat[a] = arry;
                }
            }
            String frshLn = "";
            for (int c = 0; c < 25; c++) {
                String frsh = "|";
                for (int b = 0; b < colCnt; b++) {
                    int colLen = dtstmd.getColumnName(b + 1).length();
                    if (colLen >= 3) {
                        if (Program.mustColBeFrmtd(String.valueOf(b), colsToFrmt) == true) {
                            double num = Double.parseDouble(lineFormat[b][c].trim());
                            if (!lineFormat[b][c].trim().equals("")) {
                                frsh += StringUtils.leftPad(myFormatter.format(num), colLen, ' ').substring(0,
                                        colLen);//.trim().PadRight(60, ' ')
                            } else {
                                frsh += lineFormat[b][c].substring(0, colLen); //.trim().PadRight(60, ' ')
                            }
                        } else {
                            frsh += lineFormat[b][c].substring(0, colLen); //.trim().PadRight(60, ' ')
                        }
                        frsh += "|";
                    }
                }
                String nwtst = frsh;
                frsh += "\r\n";
                if (nwtst.replace("|", " ").trim().equals("")) {
                    c = 24;
                } else {
                    frshLn += frsh;
                }
            }
            finalStr += frshLn;
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("=", colLen, '=');
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        //Populate Counts/Sums/Averages
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                if (mustColBeCntd(String.valueOf(f), colsToCnt) == true) {
                    if (mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        finalStr += "Count = " + StringUtils
                                .leftPad(myFormatter2.format(colcntVals[f]), colLen, ' ').substring(0, colLen);
                    } else {
                        finalStr += "Count = " + StringUtils
                                .rightPad(String.valueOf(colcntVals[f]), colLen, ' ').substring(0, colLen);
                    }
                } else if (mustColBeSumd(String.valueOf(f), colsToSum) == true) {
                    if (mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        finalStr += "Sum = " + StringUtils
                                .leftPad(myFormatter.format(colsumVals[f]), colLen, ' ').substring(0, colLen);
                    } else {
                        finalStr += "Sum = " + StringUtils.rightPad(String.valueOf(colsumVals[f]), colLen, ' ')
                                .substring(0, colLen);
                    }
                } else if (mustColBeAvrgd(String.valueOf(f), colsToAvrg) == true) {
                    if (mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        finalStr += "Average = " + StringUtils
                                .leftPad((myFormatter.format(colsumVals[f] / colcntVals[f])), colLen, ' ')
                                .substring(0, colLen);
                    } else {
                        finalStr += "Average = " + StringUtils
                                .rightPad((String.valueOf(colsumVals[f] / colcntVals[f])), colLen, ' ')
                                .substring(0, colLen);
                    }
                } else {
                    finalStr += StringUtils.rightPad(" ", colLen, ' ').substring(0, colLen);
                }
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        finalStr += "|";
        for (int f = 0; f < colCnt; f++) {
            int colLen = dtstmd.getColumnName(f + 1).length();
            if (colLen >= 3) {
                finalStr += StringUtils.rightPad("-", colLen, '-').substring(0, colLen);
                finalStr += "|";
            }
        }
        finalStr += "\r\n";
        return finalStr;
    } catch (SQLException ex) {
        return "";
    } catch (NumberFormatException ex) {
        return "";
    }
}