89 lines
3.4 KiB
Java
89 lines
3.4 KiB
Java
package com.minicircuits.formatter;
|
|
|
|
import com.minicircuits.QueryResult;
|
|
import com.minicircuits.Utils;
|
|
import java.io.*;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.sql.SQLException;
|
|
import java.sql.Types;
|
|
import java.util.Properties;
|
|
import javax.servlet.http.HttpServletResponse;
|
|
|
|
public class JsonFormatter implements ResponseFormatter {
|
|
|
|
public JsonFormatter(Properties configProps) {
|
|
// configProps not needed by this formatter
|
|
}
|
|
|
|
@Override
|
|
public void format(HttpServletResponse response, QueryResult result) throws IOException, SQLException {
|
|
response.setContentType("application/json");
|
|
response.setCharacterEncoding("UTF-8");
|
|
response.setBufferSize(8192);
|
|
|
|
try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream(), 8192);
|
|
OutputStreamWriter osw = new OutputStreamWriter(bos, StandardCharsets.UTF_8)) {
|
|
|
|
int colCount = result.metadata.getColumnCount();
|
|
osw.write("[");
|
|
boolean firstRow = true;
|
|
int rowCount = 0;
|
|
|
|
while (result.resultSet.next()) {
|
|
if (!firstRow) {
|
|
osw.write(",");
|
|
}
|
|
firstRow = false;
|
|
|
|
osw.write("{");
|
|
for (int i = 1; i <= colCount; i++) {
|
|
if (i > 1) osw.write(",");
|
|
String columnName = result.metadata.getColumnName(i);
|
|
String value = result.resultSet.getString(i);
|
|
|
|
int columnType = result.metadata.getColumnType(i);
|
|
String columnTypeName = result.metadata.getColumnTypeName(i);
|
|
|
|
osw.write("\"");
|
|
osw.write(Utils.escapeJson(columnName));
|
|
osw.write("\":");
|
|
if (value == null) {
|
|
osw.write("null");
|
|
} else if (Utils.isNumericType(columnType, columnTypeName)) {
|
|
try {
|
|
String trimmed = value.trim();
|
|
if (columnType == Types.FLOAT
|
|
|| columnType == Types.DOUBLE
|
|
|| columnType == Types.REAL
|
|
|| result.metadata.getScale(i) > 0) {
|
|
osw.write(String.valueOf(Double.parseDouble(trimmed)));
|
|
} else {
|
|
osw.write(String.valueOf(Long.parseLong(trimmed)));
|
|
}
|
|
} catch (NumberFormatException e) {
|
|
osw.write("\"");
|
|
osw.write(Utils.escapeJson(Utils.rightTrim(value)));
|
|
osw.write("\"");
|
|
}
|
|
} else if (columnType == Types.BOOLEAN) {
|
|
osw.write(String.valueOf(result.resultSet.getBoolean(i)));
|
|
} else {
|
|
osw.write("\"");
|
|
osw.write(Utils.escapeJson(Utils.rightTrim(value)));
|
|
osw.write("\"");
|
|
}
|
|
}
|
|
osw.write("}");
|
|
rowCount++;
|
|
|
|
if (rowCount % 1000 == 0) {
|
|
osw.flush();
|
|
}
|
|
}
|
|
|
|
osw.write("]");
|
|
osw.flush();
|
|
}
|
|
}
|
|
}
|