|
| 1 | +package com.baeldung.javaee.security; |
| 2 | + |
| 3 | +import javax.annotation.Resource; |
| 4 | +import javax.annotation.sql.DataSourceDefinition; |
| 5 | +import javax.inject.Inject; |
| 6 | +import javax.security.enterprise.identitystore.Pbkdf2PasswordHash; |
| 7 | +import javax.servlet.ServletException; |
| 8 | +import javax.servlet.annotation.WebServlet; |
| 9 | +import javax.servlet.http.HttpServlet; |
| 10 | +import javax.sql.DataSource; |
| 11 | +import java.sql.Connection; |
| 12 | +import java.sql.PreparedStatement; |
| 13 | +import java.sql.SQLException; |
| 14 | + |
| 15 | +@DataSourceDefinition( |
| 16 | + name = "java:comp/env/jdbc/securityDS", |
| 17 | + className = "org.h2.jdbcx.JdbcDataSource", |
| 18 | + url = "jdbc:h2:~/securityTest;MODE=Oracle" |
| 19 | +) |
| 20 | +@WebServlet(value = "/init", loadOnStartup = 0) |
| 21 | +public class DatabaseSetupServlet extends HttpServlet { |
| 22 | + |
| 23 | + @Resource(lookup = "java:comp/env/jdbc/securityDS") |
| 24 | + private DataSource dataSource; |
| 25 | + |
| 26 | + @Inject |
| 27 | + private Pbkdf2PasswordHash passwordHash; |
| 28 | + |
| 29 | + @Override |
| 30 | + public void init() throws ServletException { |
| 31 | + super.init(); |
| 32 | + initdb(); |
| 33 | + } |
| 34 | + |
| 35 | + private void initdb() { |
| 36 | + executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS"); |
| 37 | + executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS"); |
| 38 | + |
| 39 | + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))"); |
| 40 | + executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))"); |
| 41 | + |
| 42 | + executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')"); |
| 43 | + executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')"); |
| 44 | + |
| 45 | + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')"); |
| 46 | + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')"); |
| 47 | + executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')"); |
| 48 | + } |
| 49 | + |
| 50 | + private void executeUpdate(DataSource dataSource, String query) { |
| 51 | + try (Connection connection = dataSource.getConnection()) { |
| 52 | + try (PreparedStatement statement = connection.prepareStatement(query)) { |
| 53 | + statement.executeUpdate(); |
| 54 | + } |
| 55 | + } catch (SQLException e) { |
| 56 | + throw new IllegalStateException(e); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments