Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion servlet-security/README-source.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The `servlet-security` quickstart demonstrates the use of Jakarta EE declarative

The `servlet-security` quickstart demonstrates the use of Jakarta EE declarative security to control access to Servlets and Security in {productNameFull}.

When you deploy this example, two users are automatically created for you: user `quickstartUser` with password `quickstartPwd1!` and user `guest` with password `guestPwd1!`. This data is located in the `src/main/resources/import.sql` file.
When you deploy this example, two users are automatically created for you: user `quickstartUser` with password `quickstartPwd1!` and user `guest` with password `guestPwd1!`. This data is initialized by the `DatabaseInitializer` CDI bean on application startup.

This quickstart takes the following steps to implement Servlet security:

Expand Down
6 changes: 0 additions & 6 deletions servlet-security/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,6 @@
<scope>provided</scope>
</dependency>

<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<scope>provided</scope>
</dependency>

<!-- Import test dependencies -->
<dependency>
<groupId>org.junit.jupiter</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
Comment thread
Riovo marked this conversation as resolved.
* Copyright The WildFly Authors
* SPDX-License-Identifier: Apache-2.0
*/
package org.jboss.as.quickstarts.servlet_security;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.sql.DataSource;

import jakarta.annotation.Resource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.context.Initialized;
import jakarta.enterprise.event.Observes;

/**
* Initializes the database schema and data for Elytron JDBC realm authentication.
* This CDI bean runs at application startup to create tables and populate
* test user credentials if they don't already exist.
*
* @author Mohammed Abourass mouhammedmax@hotmail.com
*/
@ApplicationScoped
public class DatabaseInitializer {

private static final Logger LOGGER = Logger.getLogger(DatabaseInitializer.class.getName());

@Resource(lookup = "java:jboss/datasources/ServletSecurityDS")
private DataSource dataSource;

public void initializeDatabase(@Observes @Initialized(ApplicationScoped.class) Object init) {
LOGGER.info("Initializing database schema for servlet-security...");

try {
createTables();
insertTestData();
LOGGER.info("Database initialization completed successfully.");
} catch (SQLException e) {
LOGGER.log(Level.SEVERE, "Failed to initialize database", e);
throw new RuntimeException("Database initialization failed", e);
}
}

private void createTables() throws SQLException {
try (Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement()) {

// Create USERS table if not exists
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS USERS (" +
"ID INT, " +
"USERNAME VARCHAR(20), " +
"PASSWORD VARCHAR(20))"
);

// Create ROLES table if not exists
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS ROLES (" +
"ID INT, " +
"NAME VARCHAR(20))"
);

// Create USERS_ROLES junction table if not exists
stmt.executeUpdate(
"CREATE TABLE IF NOT EXISTS USERS_ROLES (" +
"USER_ID INT, " +
"ROLE_ID INT)"
);

LOGGER.info("Database tables created or verified");
}
}

private void insertTestData() throws SQLException {
try (Connection conn = dataSource.getConnection()) {

// Check if data already exists (avoid duplicates on redeployment)
if (userExists(conn, "quickstartUser")) {
LOGGER.info("Test data already exists, skipping insertion");
return;
}

// Insert users
try (PreparedStatement insertStmt = conn.prepareStatement(
"INSERT INTO USERS (ID, USERNAME, PASSWORD) VALUES (?, ?, ?)")) {

insertStmt.setInt(1, 1);
insertStmt.setString(2, "quickstartUser");
insertStmt.setString(3, "quickstartPwd1!");
insertStmt.executeUpdate();

insertStmt.setInt(1, 2);
insertStmt.setString(2, "guest");
insertStmt.setString(3, "guestPwd1!");
insertStmt.executeUpdate();
}

// Insert roles
try (PreparedStatement insertStmt = conn.prepareStatement(
"INSERT INTO ROLES (ID, NAME) VALUES (?, ?)")) {

insertStmt.setInt(1, 1);
insertStmt.setString(2, "quickstarts");
insertStmt.executeUpdate();

insertStmt.setInt(1, 2);
insertStmt.setString(2, "guest");
insertStmt.executeUpdate();
}

// Insert user-role mappings
try (PreparedStatement insertStmt = conn.prepareStatement(
"INSERT INTO USERS_ROLES (USER_ID, ROLE_ID) VALUES (?, ?)")) {

insertStmt.setInt(1, 1);
insertStmt.setInt(2, 1);
insertStmt.executeUpdate();

insertStmt.setInt(1, 2);
insertStmt.setInt(2, 2);
insertStmt.executeUpdate();
}

LOGGER.info("Test data inserted successfully");
}
}

private boolean userExists(Connection conn, String username) throws SQLException {
try (PreparedStatement stmt = conn.prepareStatement("SELECT COUNT(*) FROM USERS WHERE USERNAME = ?")) {
stmt.setString(1, username);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
return rs.getInt(1) > 0;
}
return false;
}
}
}
}

This file was deleted.

35 changes: 0 additions & 35 deletions servlet-security/src/main/resources/META-INF/persistence.xml

This file was deleted.

29 changes: 0 additions & 29 deletions servlet-security/src/main/resources/import.sql

This file was deleted.

Loading