Perhaps I just worded this question badly, but I think I found the answer to my dilemma in a different question here. I'm trying to do something very similar in being able to import arbitrary reports from databases to use them in Splunk. Formatting my results in this tabular format is somewhat more onerous, but it should work for me.
Here's an example Java class I put together for outputting the correct format in case it helps someone else.
import java.io.IOException;
import java.io.Writer;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;
import java.util.ArrayList;
public class DisplayTable {
protected List<ColumnInfo> columndata= new ArrayList<ColumnInfo>();
protected List<List<String>> data = new ArrayList<List<String>>();
private static int[] numericTypes = {Types.BIGINT, Types.DECIMAL, Types.DOUBLE, Types.FLOAT,
Types.INTEGER, Types.NUMERIC, Types.REAL, Types.SMALLINT, Types.TINYINT};
public DisplayTable() {
}
public DisplayTable(ResultSet rs) throws SQLException {
ResultSetMetaData meta = rs.getMetaData();
for (int i=1; i<=meta.getColumnCount(); i++) {
addColumn(meta.getColumnLabel(i), isNumericSqlType(meta.getColumnType(i)));
}
while (rs.next()) {
List<String> row = new ArrayList<String>();
for (int i=1; i<=meta.getColumnCount(); i++) {
row.add(rs.getObject(i).toString());
}
addRow(row);
}
}
public void addColumn(String name, boolean numeric) {
columndata.add(new ColumnInfo(name, numeric));
}
public void addColumn(String name) {
this.addColumn(name, true);
}
public void addRow(List<String> row) {
for (int i=0; i<columndata.size(); i++) {
columndata.get(i).updateMetrics(row.get(i));
}
data.add(row);
}
public void print(Writer out) throws IOException {
for (int i=0; i<columndata.size(); i++) {
out.append(columndata.get(i).formattedHeader() + " ");
}
out.append("\n");
for (List<String> row : data) {
for (int i=0; i<columndata.size(); i++) {
out.append(columndata.get(i).formatValue(row.get(i)) + " ");
}
out.append("\n");
}
}
private boolean isNumericSqlType(int type) {
for (int i=0; i<numericTypes.length; i++) {
if (type == numericTypes[i]) return true;
}
return false;
}
private class ColumnInfo {
int width;
boolean numeric;
String title;
public ColumnInfo (String name, boolean numeric) {
this.numeric = numeric;
this.title = name;
this.width = name.length();
}
public void updateMetrics(String value) {
if (value.length() > width) {
width = value.length();
}
}
private String format(String value, boolean rightjust) {
int padding = width - value.length();
StringBuilder str = new StringBuilder(width);
if (rightjust) {
for (int i=0; i<=padding; i++) {
str.append(" ");
}
str.append(value);
} else {
str.append(value);
for (int i=0; i<=padding; i++) {
str.append(" ");
}
}
return str.toString();
}
public String formatValue(String value) {
return format(value, numeric);
}
public String formattedHeader() {
return format(title, true);
}
}
}
... View more