-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDatabaseWriter.java
231 lines (200 loc) · 9.1 KB
/
DatabaseWriter.java
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package it.albertus.routerlogger.writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import it.albertus.jface.JFaceMessages;
import it.albertus.routerlogger.engine.RouterData;
import it.albertus.routerlogger.resources.Messages;
import it.albertus.util.ConfigurationException;
import it.albertus.util.StringUtils;
import it.albertus.util.logging.LoggerFactory;
import it.albertus.util.sql.SqlUtils;
public class DatabaseWriter extends Writer {
public static final String TIMESTAMP_BASE_COLUMN_NAME = "timestamp";
public static final String RESPONSE_TIME_BASE_COLUMN_NAME = "response_time_ms";
public static final byte COLUMN_NAME_MIN_LENGTH = 8;
public static final String DESTINATION_KEY = "lbl.writer.destination.database";
private static final Logger logger = LoggerFactory.getLogger(DatabaseWriter.class);
public static class Defaults {
public static final String TABLE_NAME = "router_log";
public static final String COLUMN_NAME_PREFIX = "rl_";
public static final String TIMESTAMP_COLUMN_TYPE = "TIMESTAMP";
public static final String RESPONSE_TIME_COLUMN_TYPE = "INTEGER";
public static final String INFO_COLUMN_TYPE = "VARCHAR(250)";
public static final byte COLUMN_NAME_MAX_LENGTH = 30;
public static final int CONNECTION_VALIDATION_TIMEOUT_IN_MILLIS = 2000;
private Defaults() {
throw new IllegalAccessError("Constants class");
}
}
protected static final String CFG_KEY_DB_PASSWORD = "database.password";
protected static final String CFG_KEY_DB_USERNAME = "database.username";
protected static final String CFG_KEY_DB_URL = "database.url";
protected static final String CFG_KEY_DB_DRIVER_CLASS_NAME = "database.driver.class.name";
protected static final String MSG_KEY_ERR_CONFIGURATION_REVIEW = "err.configuration.review";
protected static final String MSG_KEY_ERR_DATABASE_CFG_ERROR = "err.database.cfg.error";
protected Connection connection = null;
public DatabaseWriter() {
if (StringUtils.isBlank(configuration.getString(CFG_KEY_DB_DRIVER_CLASS_NAME))) {
throw new ConfigurationException(Messages.get(MSG_KEY_ERR_DATABASE_CFG_ERROR) + ' ' + JFaceMessages.get(MSG_KEY_ERR_CONFIGURATION_REVIEW, configuration.getFileName()), CFG_KEY_DB_DRIVER_CLASS_NAME);
}
if (StringUtils.isBlank(configuration.getString(CFG_KEY_DB_URL))) {
throw new ConfigurationException(Messages.get(MSG_KEY_ERR_DATABASE_CFG_ERROR) + ' ' + JFaceMessages.get(MSG_KEY_ERR_CONFIGURATION_REVIEW, configuration.getFileName()), CFG_KEY_DB_URL);
}
if (!configuration.contains(CFG_KEY_DB_USERNAME)) {
throw new ConfigurationException(Messages.get(MSG_KEY_ERR_DATABASE_CFG_ERROR) + ' ' + JFaceMessages.get(MSG_KEY_ERR_CONFIGURATION_REVIEW, configuration.getFileName()), CFG_KEY_DB_USERNAME);
}
if (!configuration.contains(CFG_KEY_DB_PASSWORD)) {
throw new ConfigurationException(Messages.get(MSG_KEY_ERR_DATABASE_CFG_ERROR) + ' ' + JFaceMessages.get(MSG_KEY_ERR_CONFIGURATION_REVIEW, configuration.getFileName()), CFG_KEY_DB_PASSWORD);
}
try {
Class.forName(configuration.getString(CFG_KEY_DB_DRIVER_CLASS_NAME));
}
catch (final Exception e) {
throw new ConfigurationException(Messages.get("err.database.jar", configuration.getString(CFG_KEY_DB_DRIVER_CLASS_NAME), configuration.getFileName()), e, CFG_KEY_DB_DRIVER_CLASS_NAME);
}
catch (final LinkageError le) {
throw new ConfigurationException(Messages.get("err.database.jar", configuration.getString(CFG_KEY_DB_DRIVER_CLASS_NAME), configuration.getFileName()), le, CFG_KEY_DB_DRIVER_CLASS_NAME);
}
}
@Override
public synchronized void saveInfo(final RouterData data) {
final Map<String, String> info = data.getData();
try {
boolean showMessage = false;
// Connessione al database...
if (connection == null || !connection.isValid(configuration.getInt("database.connection.validation.timeout.ms", Defaults.CONNECTION_VALIDATION_TIMEOUT_IN_MILLIS))) {
connection = DriverManager.getConnection(configuration.getString(CFG_KEY_DB_URL), configuration.getString(CFG_KEY_DB_USERNAME), configuration.getString(CFG_KEY_DB_PASSWORD));
connection.setAutoCommit(true);
showMessage = true;
}
// Verifica esistenza tabella ed eventuale creazione...
final String tableName = getTableName();
if (!tableExists(tableName)) {
logger.log(Level.INFO, Messages.get("msg.creating.database.table"), tableName);
createTable(tableName, info);
showMessage = true;
}
// Inserimento dati...
if (showMessage) {
logger.log(Level.INFO, Messages.get("msg.logging.into.database"), tableName);
}
final Map<Integer, String> columns = new HashMap<Integer, String>();
final StringBuilder dml = new StringBuilder("INSERT INTO ").append(tableName).append(" (").append(getTimestampColumnName());
dml.append(", ").append(getResponseTimeColumnName());
int index = 3;
for (final String key : info.keySet()) {
columns.put(index++, key);
dml.append(", ").append(getColumnName(key));
}
dml.append(") VALUES (?, ?");
for (int i = 0; i < info.size(); i++) {
dml.append(", ?");
}
dml.append(')');
final String sql = dml.toString();
showSql(sql);
PreparedStatement insert = null;
try {
insert = connection.prepareStatement(sql);
insert.setTimestamp(1, new Timestamp(data.getTimestamp().getTime()));
insert.setInt(2, data.getResponseTime());
for (final Entry<Integer, String> entry : columns.entrySet()) {
insert.setString(entry.getKey(), info.get(entry.getValue()));
}
insert.executeUpdate();
}
finally {
SqlUtils.closeQuietly(insert);
}
}
catch (final Exception e) { // In caso di errore, chiudere la connessione al database.
closeDatabaseConnection();
throw new DatabaseException(e);
}
}
protected String getResponseTimeColumnName() {
return getColumnName(RESPONSE_TIME_BASE_COLUMN_NAME);
}
protected String getTimestampColumnName() {
return getColumnName(TIMESTAMP_BASE_COLUMN_NAME);
}
protected boolean tableExists(final String tableName) {
PreparedStatement statement = null;
try {
// Verifica esistenza tabella...
final String sql = "SELECT 1 FROM " + SqlUtils.sanitizeName(tableName);
showSql(sql);
statement = connection.prepareStatement(sql);
statement.setFetchSize(1);
statement.executeQuery();
return true;
}
catch (final SQLException e) {
logger.log(Level.FINER, e.toString(), e);
return false;
}
finally {
SqlUtils.closeQuietly(statement);
}
}
protected void createTable(final String tableName, final Map<String, String> info) throws SQLException {
final String timestampColumnType = SqlUtils.sanitizeType(configuration.getString("database.timestamp.column.type", Defaults.TIMESTAMP_COLUMN_TYPE));
final String responseTimeColumnType = SqlUtils.sanitizeType(configuration.getString("database.response.column.type", Defaults.RESPONSE_TIME_COLUMN_TYPE));
final String infoColumnType = SqlUtils.sanitizeType(configuration.getString("database.info.column.type", Defaults.INFO_COLUMN_TYPE));
// Creazione tabella...
StringBuilder ddl = new StringBuilder("CREATE TABLE ").append(tableName).append(" (").append(getTimestampColumnName()).append(' ').append(timestampColumnType);
ddl.append(", ").append(getResponseTimeColumnName()).append(' ').append(responseTimeColumnType); // Response time
for (String key : info.keySet()) {
ddl.append(", ").append(getColumnName(key)).append(' ').append(infoColumnType);
}
ddl.append(", CONSTRAINT pk_routerlogger PRIMARY KEY (").append(getTimestampColumnName()).append("))");
PreparedStatement createTable = null;
final String sql = ddl.toString();
showSql(sql);
try {
createTable = connection.prepareStatement(sql);
createTable.executeUpdate();
}
finally {
SqlUtils.closeQuietly(createTable);
}
}
protected String getTableName() {
return SqlUtils.sanitizeName(configuration.getString("database.table.name", Defaults.TABLE_NAME));
}
protected String getColumnName(final String name) {
String completeName = SqlUtils.sanitizeName(configuration.getString("database.column.name.prefix", Defaults.COLUMN_NAME_PREFIX) + name);
final int maxLength = configuration.getInt("database.column.name.max.length", Defaults.COLUMN_NAME_MAX_LENGTH);
if (completeName.length() > maxLength) {
completeName = completeName.substring(0, maxLength);
}
return completeName;
}
@Override
public void release() {
closeDatabaseConnection();
}
protected void closeDatabaseConnection() {
try {
if (connection != null && !connection.isClosed()) {
logger.info(Messages.get("msg.closing.database.connection"));
connection.close();
connection = null;
}
}
catch (final SQLException e) {
logger.log(Level.FINE, e.toString(), e);
}
}
protected void showSql(final String sql) {
logger.fine(sql);
}
}