A self hosted chat application with end-to-end encrypted messaging.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

83 lines
2.7 KiB

package org.ros.chatto.service;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.ros.chatto.config.DBInitializerConfig;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Service
@Slf4j
@RequiredArgsConstructor
public class DBInitializerService {
private final DBInitializerConfig dbInitializerConfig;
@PersistenceContext
private EntityManager entityManager;
public int getNumTables(final Connection connection) throws SQLException {
final PreparedStatement preparedStatement = connection.prepareStatement(dbInitializerConfig.getNumTablesQuery());
preparedStatement.setString(1, dbInitializerConfig.getDbName());
final ResultSet resultSet = preparedStatement.executeQuery();
resultSet.next();
final int numTables = resultSet.getInt("num_tables");
return numTables;
}
@EventListener(ApplicationReadyEvent.class)
@Transactional
public void doSomethingAfterStartup() throws SQLException, IOException {
log.info("Application Started - running initializer service");
final Session session = entityManager.unwrap(Session.class);
session.doWork(connection -> {
if (getNumTables(connection) == 0) {
log.info("Database is empty. Populating tables and roles");
try {
populateDB(connection);
} catch (final IOException e) {
log.error("IO error", e);
}
}
});
session.doWork(connection -> {
log.info("Resetting all user sessions");
resetAllUserSessions(connection);
});
}
private void populateDB(final Connection connection) throws SQLException, IOException {
ScriptUtils.executeSqlScript(connection,
new EncodedResource(new ClassPathResource("scheme.sql"), StandardCharsets.UTF_8));
ScriptUtils.executeSqlScript(connection,
new EncodedResource(new ClassPathResource("datae.sql"), StandardCharsets.UTF_8));
}
private void resetAllUserSessions(final Connection connection) throws SQLException {
final PreparedStatement preparedStatement = connection.prepareStatement(dbInitializerConfig.getResetSessionsQuery());
preparedStatement.executeUpdate();
}
}