Skip to content

Commit

Permalink
Feat: Added back Roar verify function
Browse files Browse the repository at this point in the history
  • Loading branch information
AdrianBalunan committed Mar 12, 2026
1 parent 38a0e59 commit c756c1c
Showing 1 changed file with 154 additions and 114 deletions.
Original file line number Diff line number Diff line change
@@ -1,67 +1,64 @@
package ntnu.systemutvikling.team6.database;

import ntnu.systemutvikling.team6.models.Charity;
import ntnu.systemutvikling.team6.models.CharityRegistry;
import ntnu.systemutvikling.team6.scraper.APICharityData;

import java.sql.*;
import java.util.List;
import java.util.UUID;

import ntnu.systemutvikling.team6.models.Charity;
import ntnu.systemutvikling.team6.scraper.APICharityData;

/**
* Manages creation of MySQL tables (for now)
* <p>
* This class is responsible for creating the tables needed for the application, if not done already
* and maintaining the {@code charities} table based on data retrieved from the IK API.
* </p>
*
* <p>This class is responsible for creating the tables needed for the application, if not done
* already and maintaining the {@code charities} table based on data retrieved from the IK API.
*/

public class DatabaseManager {
private final DatabaseConnection connection;

/**
* Contractor for DatabaseManager. It uses a DatabaseConnection object that contains a connection credentials
* using environment variables in the DatabaseConnection.
*/
public DatabaseManager(){
this.connection = new DatabaseConnection();
private final DatabaseConnection connection;

/**
* Contractor for DatabaseManager. It uses a DatabaseConnection object that contains a connection
* credentials using environment variables in the DatabaseConnection.
*/
public DatabaseManager() {
this.connection = new DatabaseConnection();
}

/**
* Connection test for the Database. Does a simple SELECT SQL query and returns either true og and
* Exception if failed
*
* @return true if Sucsedd or SQLExepction if failed
*/
public boolean testConnection() {
try (Connection conn = connection.getMySqlConnection();
Statement stmt = conn.createStatement()) {

ResultSet rs = stmt.executeQuery("SELECT 1");

if (rs.next()) {
System.out.println("Database connection verified.");
return true;
}

} catch (SQLException e) {
System.out.println("Database connection failed.");
e.printStackTrace();
}

/**
* Connection test for the Database.
* Does a simple SELECT SQL query and returns either true og and Exception if failed
*
* @return true if Sucsedd or SQLExepction if failed
*/
public boolean testConnection() {
try (Connection conn = connection.getMySqlConnection();
Statement stmt = conn.createStatement()) {

ResultSet rs = stmt.executeQuery("SELECT 1");

if (rs.next()) {
System.out.println("Database connection verified.");
return true;
}

} catch (SQLException e) {
System.out.println("Database connection failed.");
e.printStackTrace();
}

return false;
}

/**
* Creates the {@code charities} table if it does not already exist.
* <p>
* The table structure is based on fields from {@link APICharityData}.
* </p>
* @throws RuntimeException if a {@link SQLException} occurs while creating the table
*/

public void createTables() {
String sql_query1 =
"""
return false;
}

/**
* Creates the {@code charities} table if it does not already exist.
*
* <p>The table structure is based on fields from {@link APICharityData}.
*
* @throws RuntimeException if a {@link SQLException} occurs while creating the table
*/
public void createTables() {
String sql_query1 =
"""
-- -----------------------------------------------------
-- Table `HelpMeHelp`.`Charities`
-- -----------------------------------------------------
Expand All @@ -75,10 +72,10 @@ status VARCHAR(255) NOT NULL,
UNIQUE KEY unique_org_number (org_number)
) ENGINE=InnoDB;
""";
String sql_query2 =
"""
String sql_query2 =
"""
-- -----------------------------------------------------
-- Table `HelpMeHelp`.`Donations`
-- -----------------------------------------------------
Expand All @@ -91,74 +88,117 @@ PRIMARY KEY (`UUID_Donations`),
INDEX `fk_Donations_Charities_idx` (`Charities_UUID_charities` ASC) VISIBLE,
CONSTRAINT `fk_Donations_Charities`
FOREIGN KEY (`Charities_UUID_charities`)
REFERENCES `apbaluna`.`Charities` (`UUID_charities`)
REFERENCES Charities (`UUID_charities`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
""";

try (Connection conn = connection.getMySqlConnection();
Statement s = conn.createStatement()) {
try (Connection conn = connection.getMySqlConnection();
Statement s = conn.createStatement()) {

s.execute(sql_query1);
s.execute(sql_query2);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Error creating table.");
}
s.execute(sql_query1);
s.execute(sql_query2);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("Error creating table.");
}

public void addAPIDataToTable(List<Charity> charities){
Connection conn = null;
try {
conn = connection.getMySqlConnection();
conn.setAutoCommit(false);
String sql_query = """
INSERT IGNORE INTO Charities (UUID_charities, org_number, charity_name, charity_link, pre_approved, status)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
charity_name = VALUES(charity_name),
charity_link = VALUES(charity_link),
pre_approved = VALUES(pre_approved),
status = VALUES(status)
}

public void addAPIDataToTable(List<Charity> charities) {
Connection conn = null;
try {
conn = connection.getMySqlConnection();
conn.setAutoCommit(false);
String sql_query =
"""
INSERT INTO Charities (UUID_charities, org_number, charity_name, charity_link, pre_approved, status)
VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
charity_name = VALUES(charity_name),
charity_link = VALUES(charity_link),
pre_approved = VALUES(pre_approved),
status = VALUES(status)
""";

try (PreparedStatement ps = conn.prepareStatement(sql_query)) {
for (Charity charity : charities) {
ps.setString(1, charity.getUUID().toString());
ps.setString(2, charity.getOrg_number().replaceAll("\\s", ""));
ps.setString(3, charity.getName());
ps.setString(4, charity.getDescription());
ps.setBoolean(5, charity.getPreApproved()); // Description is the link
ps.setString(6, charity.getStatus());

ps.addBatch();
}
ps.executeBatch();
}
conn.commit();
try (PreparedStatement ps = conn.prepareStatement(sql_query)) {
for (Charity charity : charities) {
if (charity.getUUID() == null) {
ps.setString(1, UUID.randomUUID().toString());
} else {
ps.setString(1, charity.getUUID().toString());
}

ps.setString(1, charity.getUUID().toString());
ps.setString(2, charity.getOrg_number().replaceAll("\\s", ""));
ps.setString(3, charity.getName());
ps.setString(4, charity.getDescription());
ps.setBoolean(5, charity.getPreApproved()); // Description is the link
ps.setString(6, charity.getStatus());

ps.addBatch();
}
ps.executeBatch();
}

// -- Intergerty Check:
String createTemp = """
CREATE TEMPORARY TABLE temp_api_charities (
org_number VARCHAR(255) PRIMARY KEY
)
""";

} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();

throw new RuntimeException("ERROR: Something went wrong during updating charities table.");
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
try (PreparedStatement ps = conn.prepareStatement(createTemp)) {
ps.execute();
}

String insertTemp = "INSERT INTO temp_api_charities (org_number) VALUES (?)";

try (PreparedStatement ps = conn.prepareStatement(insertTemp)) {

for (Charity charity : charities) {
ps.setString(1, charity.getOrg_number().replaceAll("\\s",""));
ps.addBatch();
}

ps.executeBatch();
}

String deleteSql = """
DELETE FROM Charities c
WHERE NOT EXISTS (
SELECT 1
FROM temp_api_charities t
WHERE t.org_number = c.org_number
)
""";

try (PreparedStatement ps = conn.prepareStatement(deleteSql)) {
ps.executeUpdate();
}

conn.commit();

} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();

throw new RuntimeException("ERROR: Something went wrong during updating charities table.");
} finally {
if (conn != null) {
try {
conn.setAutoCommit(true);
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}

0 comments on commit c756c1c

Please sign in to comment.