This repository was archived by the owner on Jul 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResultMapper.java
More file actions
79 lines (69 loc) · 2.76 KB
/
ResultMapper.java
File metadata and controls
79 lines (69 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.planner.api.database;
import com.planner.api.model.QueryResponse;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ResultMapper {
/**
* <ol>
* <li>Extract column definition.</li>
* <li>Extract rows as defined from the column definition.</li>
* <li>Collects possible errors from the rows.</li>
* </ol>
*
* @param resultSet for data extraction
* @return extracted response
* @throws SQLException if a database access error occurs or this method is called on a closed result set
*/
public static QueryResponse resultToResponse(ResultSet resultSet) throws SQLException {
QueryResponse queryResult = new QueryResponse();
queryResult.columnDef = extractColumnDef(resultSet);
// go through result set
while (resultSet.next()) {
queryResult.instanceCount++;
try {
// extract data
queryResult.rows.add(extractRow(queryResult.columnDef, resultSet));
} catch (Exception exception) {
// log error
queryResult.errorCount++;
queryResult.errorMessages.add(exception.getClass().getSimpleName() + ": " + exception.getMessage());
}
}
return queryResult;
}
/**
* Extract column definition of the metadata.
*
* @param resultSet for column definition
* @return map of column definition <array index, column name>
* @throws SQLException if a database access error occurs
*/
private static List<String> extractColumnDef(ResultSet resultSet) throws SQLException {
List<String> columnDef = new ArrayList<>();
ResultSetMetaData metaData = resultSet.getMetaData();
for (int colIndex = 0; colIndex < metaData.getColumnCount(); colIndex++) {
// meta data column count starts at 1
columnDef.add(metaData.getColumnLabel(colIndex + 1));
}
return columnDef;
}
/**
* Extract row of result set, with the definition (order) of the column definition.
*
* @param columnDef for row definition
* @param resultSet to extract row from
* @return row as array
* @throws SQLException if the columnLabel is not valid; if a database access error occurs or this method is called on a closed result set
*/
private static Object[] extractRow(List<String> columnDef, ResultSet resultSet) throws SQLException {
Object[] row = new Object[columnDef.size()];
for (int i = 0; i < columnDef.size(); i++) {
// meta data column count starts at 1
row[i] = resultSet.getObject(i + 1);
}
return row;
}
}