Class DatabaseManagement
java.lang.Object
org.noise_planet.noisemodelling.webserver.database.DatabaseManagement
Handle the creation of datasource according to application configuration
The Model of the Web Server
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic intaddUser(Connection connection, String email, Role... roles) This method adds a new user with the provided email.static com.zaxxer.hikari.HikariDataSourcecreateH2DataSource(String databaseDirectory, String databaseName, String userName, String userPassword, String secureBaseEncryptionSecret, boolean initializeSpatial) Create H2Database datasourcestatic intcreateJob(Connection connection, int userIdentifier, String jobScript) Create a new job with the specified user and return the job identifierstatic voidcreateServerDataBaseStructure(Connection connection) static XMLGregorianCalendardateToXMLGregorianCalendar(String stringDate) static voiddeleteAllFinalizedJobs(Connection connection, int identifier) Deletes all jobs from the JOBS table that are not in the 'QUEUED' or 'RUNNING' status.static voiddeleteJob(Connection connection, int jobId) Deletes a job record from the JOBS table based on the specified job ID.static voiddeleteUser(Connection connection, int userIdentifier) static StringBuildergetConnectionUrl(String databaseDirectory, String databaseName, boolean databaseEncryption) Build H2 connection URLgetJob(Connection connection, int jobId) Fetch the content of the JOB tablegetJobs(Connection connection, int filterByUserIdentifier) Fetch the content of the JOB tablestatic StringgetJWTSigningKey(DataSource serverDataSource) Retrieve the generated signing key of the server That key is used to sign the JWT tokens provided to the users If a malicious user tries to change the payload (ex. user identifier), then the token will not be validstatic StringgetTotpSecretByUserEmail(Connection connection, String email) Get user by register tokenstatic UsergetUser(Connection connection, int userIdentifier) Get user from databasestatic UsergetUser(Connection connection, ResultSet rsUser) static UsergetUser(DataSource serverDataSource, int userIdentifier) Get user from databasestatic intgetUserByRegisterToken(Connection connection, String registerToken) Get user by register tokenstatic intgetUserIdByUserEmail(Connection connection, String email) Get user id by using emailgetUserRoles(Connection connection, int userIdentifier) Get user rolesgetUsers(Connection connection) static voidinitializeServerDatabaseStructure(DataSource dataSource, Configuration configuration) parseJob(ResultSet rs, DateFormat mediumDateFormatEN, DecimalFormat f) static voidsetJobEndTime(Connection connection, int jobId) static voidsetJobProgression(Connection connection, int jobId, double progression) static voidsetJobState(Connection connection, int jobId, String jobState) Update the state of an existing Job record.static voidupdateUserAttributes(Connection connection, User user) Updates the user attributes (email, totp token) in the database.static voidupdateUserTotpToken(Connection connection, int userIdentifier, String totpToken) Updates the TOTP token for a user and clears their registerToken field.
-
Field Details
-
DATABASE_VERSION
public static final int DATABASE_VERSION- See Also:
-
ADMIN_EMAIL
- See Also:
-
mediumDateFormatEN
-
-
Constructor Details
-
DatabaseManagement
public DatabaseManagement()
-
-
Method Details
-
createH2DataSource
public static com.zaxxer.hikari.HikariDataSource createH2DataSource(String databaseDirectory, String databaseName, String userName, String userPassword, String secureBaseEncryptionSecret, boolean initializeSpatial) throws SQLException Create H2Database datasource- Parameters:
databaseDirectory- Where to store the databasedatabaseName- Name of the databaseuserName- Admin usernameuserPassword- Admin passwordsecureBaseEncryptionSecret- Encryption database password, optional (empty)initializeSpatial- If true initialize H2GIS- Returns:
- DataSource instance
- Throws:
SQLException- If something wrong happened
-
getConnectionUrl
@NotNull public static StringBuilder getConnectionUrl(String databaseDirectory, String databaseName, boolean databaseEncryption) Build H2 connection URL- Parameters:
databaseDirectory- Database directorydatabaseName- Database namedatabaseEncryption- True to enable encryption- Returns:
- Connection URL
-
initializeServerDatabaseStructure
public static void initializeServerDatabaseStructure(DataSource dataSource, Configuration configuration) throws SQLException - Throws:
SQLException
-
createServerDataBaseStructure
- Throws:
SQLException
-
getJWTSigningKey
Retrieve the generated signing key of the server That key is used to sign the JWT tokens provided to the users If a malicious user tries to change the payload (ex. user identifier), then the token will not be valid- Parameters:
serverDataSource- data source- Returns:
- JWTSigningKey
- Throws:
SQLException- Something went wrong
-
getUserRoles
public static List<String> getUserRoles(Connection connection, int userIdentifier) throws SQLException Get user roles- Parameters:
connection- Data source to the databaseuserIdentifier- User identifier in the database (e.g., primary key)- Returns:
- List of roles associated with the user
- Throws:
SQLException- If something wrong happened
-
getUser
Get user from database- Parameters:
serverDataSource- Data source to the databaseuserIdentifier- User identifier in the database (e.g., primary key)- Returns:
- User object with associated roles and details
- Throws:
SQLException- If something wrong happened
-
getUser
Get user from database- Parameters:
connection- Data source to the databaseuserIdentifier- User identifier in the database (e.g., primary key)- Returns:
- User object with associated roles and details
- Throws:
SQLException- If something wrong happened
-
getUser
- Throws:
SQLException
-
addUser
This method adds a new user with the provided email.It generates an expected token that would be provided in the url when associating to a TOTP generator This token is provided to the user with the server url by mail or other communication method.
- Parameters:
connection- The database Connection object used to execute the query.email- The email of the user to be added.- Returns:
- The token generated for this new user.
- Throws:
SQLException- If the operation fails to add a user (i.e., no rows are affected in the "USERS" table).
-
getUserByRegisterToken
public static int getUserByRegisterToken(Connection connection, String registerToken) throws SQLException Get user by register token- Parameters:
connection- The database Connection objectregisterToken- The registration token from URL- Returns:
- User identifier or -1 if not found
- Throws:
SQLException- If database error occurs
-
updateUserTotpToken
public static void updateUserTotpToken(Connection connection, int userIdentifier, String totpToken) throws SQLException Updates the TOTP token for a user and clears their registerToken field.- Parameters:
connection- The database connection object.userIdentifier- The unique identifier of the user in the database.totpToken- The new Time-Based One-Time Password (TOTP) token to be assigned to the user.- Throws:
SQLException- If there's an error executing the SQL update or if no rows were affected, indicating that no user with the given identifier was found in the database.
-
getTotpSecretByUserEmail
public static String getTotpSecretByUserEmail(Connection connection, String email) throws SQLException Get user by register token- Parameters:
connection- The database Connection objectemail- User email- Returns:
- User TOTP_TOKEN or empty if not found
- Throws:
SQLException- If database error occurs
-
getUserIdByUserEmail
Get user id by using email- Parameters:
connection- The database Connection objectemail- User email- Returns:
- User identifier or -1 if not found
- Throws:
SQLException- If database error occurs
-
createJob
public static int createJob(Connection connection, int userIdentifier, String jobScript) throws SQLException Create a new job with the specified user and return the job identifier- Parameters:
connection- SQL ConnectionuserIdentifier- User identifier- Returns:
- Job identifier
- Throws:
SQLException- Error
-
setJobState
public static void setJobState(Connection connection, int jobId, String jobState) throws SQLException Update the state of an existing Job record.Persists the given state in table
JOBSfor the row identified byPK_JOB. ThejobStateis expected to be the name of a value fromJobStates(e.g.QUEUED,RUNNING, etc.).- Parameters:
connection- The open JDBCConnectionto use; must not benull.jobId- The identifier of the job to update (value of columnPK_JOB).jobState- The new state to set for the job (typicallyJobStates.name()).- Throws:
SQLException- If a database access error occurs, or if no row was updated (job not found).
-
setJobProgression
public static void setJobProgression(Connection connection, int jobId, double progression) throws SQLException - Throws:
SQLException
-
setJobEndTime
- Throws:
SQLException
-
getJobs
public static List<Map<String,Object>> getJobs(Connection connection, int filterByUserIdentifier) throws SQLException Fetch the content of the JOB table- Parameters:
connection-filterByUserIdentifier- if> 0, will filter the job for a specific user. Administrator see all jobs.- Returns:
- Job list
- Throws:
SQLException
-
dateToXMLGregorianCalendar
public static XMLGregorianCalendar dateToXMLGregorianCalendar(String stringDate) throws SQLException, ParseException, DatatypeConfigurationException - Parameters:
stringDate-- Throws:
SQLExceptionParseExceptionDatatypeConfigurationException
-
getJob
Fetch the content of the JOB table- Parameters:
connection-jobId- if> 0, will filter the job for a specific user. Administrator see all jobs.- Returns:
- Job list
- Throws:
SQLException
-
parseJob
@NotNull public static Map<String,Object> parseJob(ResultSet rs, DateFormat mediumDateFormatEN, DecimalFormat f) throws SQLException - Throws:
SQLException
-
getUsers
- Throws:
SQLException
-
updateUserAttributes
Updates the user attributes (email, totp token) in the database.- Parameters:
connection- The database connection object.user- New attributes for the user.- Throws:
SQLException- If there's an error executing the SQL update or if no rows were affected, indicating that no user with the given identifier was found in the database.
-
deleteUser
- Throws:
SQLException
-
deleteJob
Deletes a job record from the JOBS table based on the specified job ID.- Parameters:
connection- The database connection to be used for executing the query.jobId- The ID of the job to be deleted.- Throws:
SQLException- If a database access error occurs or the SQL statement fails to execute.
-
deleteAllFinalizedJobs
public static void deleteAllFinalizedJobs(Connection connection, int identifier) throws SQLException Deletes all jobs from the JOBS table that are not in the 'QUEUED' or 'RUNNING' status.- Parameters:
connection- the active database connection to use for executing the deletion queryidentifier- User identifier- Throws:
SQLException- if a database access error occurs or the SQL statement fails
-