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
|
package org.openslx.bwlp.sat.database.mappers;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.openslx.bwlp.sat.database.Database;
import org.openslx.bwlp.sat.database.MysqlConnection;
import org.openslx.bwlp.sat.database.MysqlStatement;
public class DbConfiguration {
private static final Logger LOGGER = Logger.getLogger(DbConfiguration.class);
private static final String KEY_CERTIFICATE = "certstore";
public static KeyStore loadKeyStore(String password) throws KeyStoreException, SQLException,
NoSuchAlgorithmException, CertificateException, IOException {
KeyStore keystore = KeyStore.getInstance("JKS");
InputStream stream = retrieveStream(KEY_CERTIFICATE);
if (stream == null)
return null;
keystore.load(stream, password.toCharArray());
return keystore;
}
public static void saveKeyStore(File file) throws SQLException, FileNotFoundException, IOException {
store(KEY_CERTIFICATE, new FileInputStream(file));
}
private static void store(String configKey, InputStream stream) throws IOException, SQLException {
store(configKey, IOUtils.toByteArray(stream));
}
private static void store(String configKey, byte[] value) throws SQLException {
try (MysqlConnection connection = Database.getConnection()) {
MysqlStatement stmt = connection.prepareStatement("INSERT INTO configuration"
+ " (parameter, value) VALUES (:parameter, :value)"
+ " ON DUPLICATE KEY UPDATE value = VALUES(value)");
stmt.setString("parameter", configKey);
stmt.setBinary("value", value);
stmt.executeUpdate();
connection.commit();
} catch (SQLException e) {
LOGGER.error("Query failed in DbConfiguration.store()", e);
throw e;
}
}
private static InputStream retrieveStream(String configKey) throws SQLException {
byte[] data = retrieve(configKey);
if (data == null)
return null;
return new ByteArrayInputStream(data);
}
private static byte[] retrieve(String configKey) throws SQLException {
try (MysqlConnection connection = Database.getConnection()) {
MysqlStatement stmt = connection.prepareStatement("SELECT value FROM configuration"
+ " WHERE parameter = :parameter LIMIT 1");
stmt.setString("parameter", configKey);
ResultSet rs = stmt.executeQuery();
if (!rs.next())
return null;
return rs.getBytes("value");
} catch (SQLException e) {
LOGGER.error("Query failed in DbConfiguration.retrieve()", e);
throw e;
}
}
}
|