From 03e933e0c5b1ff4d4e0428177eacf33c514c0041 Mon Sep 17 00:00:00 2001 From: suryabahadurkathayat Date: Tue, 6 Jan 2026 10:32:40 +0100 Subject: [PATCH] initial --- .gitignore | 5 + .../java/no/ntnu/idatx1005/demo/MyApp.java | 18 +++ .../dao/PostgresDBConnectionProvider.java | 105 ++++++++++++++++++ .../no/ntnu/idatx1005/demo/dao/UserDAO.java | 93 ++++++++++++++++ .../no/ntnu/idatx1005/demo/data/MyEntity.java | 37 ++++++ .../no/ntnu/idatx1005/demo/data/User.java | 45 ++++++++ .../idatx1005/demo/repo/MyEntityRepo.java | 46 ++++++++ .../no/ntnu/idatx1005/demo/view/MyWindow.java | 45 ++++++++ src/main/resources/db | 0 .../ntnu/idatx1005/demo/dao/DatabaseTest.java | 36 ++++++ .../idatx1005/demo/repo/MyEntityRepoTest.java | 25 +++++ src/test/resources/testdb | 0 12 files changed, 455 insertions(+) create mode 100644 src/main/java/no/ntnu/idatx1005/demo/MyApp.java create mode 100644 src/main/java/no/ntnu/idatx1005/demo/dao/PostgresDBConnectionProvider.java create mode 100644 src/main/java/no/ntnu/idatx1005/demo/dao/UserDAO.java create mode 100644 src/main/java/no/ntnu/idatx1005/demo/data/MyEntity.java create mode 100644 src/main/java/no/ntnu/idatx1005/demo/data/User.java create mode 100644 src/main/java/no/ntnu/idatx1005/demo/repo/MyEntityRepo.java create mode 100644 src/main/java/no/ntnu/idatx1005/demo/view/MyWindow.java create mode 100644 src/main/resources/db create mode 100644 src/test/java/no/ntnu/idatx1005/demo/dao/DatabaseTest.java create mode 100644 src/test/java/no/ntnu/idatx1005/demo/repo/MyEntityRepoTest.java create mode 100644 src/test/resources/testdb diff --git a/.gitignore b/.gitignore index 524f096..9332ae8 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,8 @@ # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml hs_err_pid* replay_pid* + +.idea +*.idea/ + +*.DS_Store \ No newline at end of file diff --git a/src/main/java/no/ntnu/idatx1005/demo/MyApp.java b/src/main/java/no/ntnu/idatx1005/demo/MyApp.java new file mode 100644 index 0000000..fa29d40 --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/MyApp.java @@ -0,0 +1,18 @@ +package no.ntnu.idatx1005.demo; + +import no.ntnu.idatx1005.demo.view.MyWindow; + +/** + * Use this class to start the application + * @author nilstes + */ +public class MyApp { + + /** + * Main method for my application + */ + public static void main(String[] args) throws Exception { + MyWindow window = new MyWindow("The Window"); + window.setVisible(true); + } +} diff --git a/src/main/java/no/ntnu/idatx1005/demo/dao/PostgresDBConnectionProvider.java b/src/main/java/no/ntnu/idatx1005/demo/dao/PostgresDBConnectionProvider.java new file mode 100644 index 0000000..4dc43fd --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/dao/PostgresDBConnectionProvider.java @@ -0,0 +1,105 @@ +package no.ntnu.idatx1005.demo.dao; + + +import java.sql.*; + +public class PostgresDBConnectionProvider { + private static PostgresDBConnectionProvider databaseConnectionProvider; + private static String DB_NAME = "idatt1005-db"; + private static String DATABASE_URL = "jdbc:postgresql://localhost:5432/" + DB_NAME; + private static String username = "idatt1005user"; + private static String password = "idatt1005password"; + + public PostgresDBConnectionProvider() { + } + + Connection getConnection() { + try { + // Note: In a real application, you should not connect to the database like this. Instead, you should use a connection pool. + // In addition, database should be protected + return DriverManager.getConnection(DATABASE_URL, username, password); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static PostgresDBConnectionProvider instance() { + if (databaseConnectionProvider == null) { + databaseConnectionProvider = new PostgresDBConnectionProvider(); + return databaseConnectionProvider; + } else { + return databaseConnectionProvider; + } + } + + /** + * Closes connections to database, makes sure that resultSets, and statements gets closed properly + * @param connection the connection to be closed + * @param preparedStatement the preparedStatement to be closed + * @param resultSet the resultSet to be closed + */ + static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (preparedStatement != null) { + try { + preparedStatement.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + } + + /** + * Method that creates a database if it does not exist. + * Note that you should not use this method in production code. Instead, you should create the database tables via SQL scripts. + * The method creates tables for User. + * + * @throws SQLException if creating the database fails + */ + public static void createDB() throws SQLException { + + try (Connection connection = DriverManager.getConnection(DATABASE_URL)) { + + // Sql-statements for creating tables + // NOTE: Passwords should never be stored in plain text in a real/production application. They should be hashed and salted. + String createUserTable = + "CREATE TABLE IF NOT EXISTS Users (" + + "userId uuid primary key, " + + "username VARCHAR(255), " + + "password VARCHAR(255)" + + ");"; + executeStatement(connection, createUserTable); + } catch (SQLException e) { + throw new SQLException("Error creating tables: " + e.getMessage(), e); + } + } + + /** + * Method that executes a sql statement. + * + * @param connection connection to the database + * @param sql the sql statement to execute + * @throws SQLException if executing the statement fails + */ + private static void executeStatement(Connection connection, String sql) throws SQLException { + try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) { + preparedStatement.executeUpdate(); + } catch (SQLException e) { + throw new SQLException("Error executing statement: " + e.getMessage(), e); + } + } + +} diff --git a/src/main/java/no/ntnu/idatx1005/demo/dao/UserDAO.java b/src/main/java/no/ntnu/idatx1005/demo/dao/UserDAO.java new file mode 100644 index 0000000..317ab4d --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/dao/UserDAO.java @@ -0,0 +1,93 @@ +package no.ntnu.idatx1005.demo.dao; + +import no.ntnu.idatx1005.demo.data.User; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Data access object for User + */ +public class UserDAO { + private PostgresDBConnectionProvider connectionProvider; + + public UserDAO(PostgresDBConnectionProvider connectionProvider) { + this.connectionProvider = connectionProvider; + } + + /** + * Returns a List of all registered users + * + * @return List of Users + */ + public List getUsers() { + List users = new ArrayList<>(); + PreparedStatement preparedStatement = null; + Connection connection = null; + ResultSet resultSet = null; + try { + connection = connectionProvider.getConnection(); + preparedStatement = connection.prepareStatement("SELECT * FROM userinfo"); + resultSet = preparedStatement.executeQuery(); + + User user; + while (resultSet.next()) { + user = new User(); + user.setUserid(UUID.fromString(resultSet.getString("userId"))); + user.setUsername(resultSet.getString("username")); + users.add(user); + } + } catch (SQLException e) { + e.printStackTrace(); + } finally { + PostgresDBConnectionProvider.close(connection, preparedStatement, resultSet); + } + return users; + } + + /** + * Adds a new user to database with default ID + * + * @param user User object + * @return new User or already registered user + */ + public User addUser(User user) { + Connection connection = null; + PreparedStatement preparedStatement = null; + ResultSet resultSet = null; + + // check if user already exists in database + User existingUser = getUsers().stream().allMatch(u -> u.getUsername().equals(user.getUsername())) ? user : null; + if(existingUser != null) { + System.out.println("User already exists"); + return existingUser; + } + + try { + connection = connectionProvider.getConnection(); + User newUser = new User(); + preparedStatement = connection.prepareStatement("INSERT INTO userinfo (userId, username, password) VALUES (?, ?, ?)", Statement.RETURN_GENERATED_KEYS); + preparedStatement.setObject(1, user.getUserid(), Types.OTHER); + preparedStatement.setString(2, user.getUsername()); + preparedStatement.setString(3, user.getPassword()); + int result = preparedStatement.executeUpdate(); + + if (result == 1) { + newUser.setUsername(user.getUsername()); + newUser.setUserid(user.getUserid()); + return newUser; + } + } catch (SQLException e) { + e.printStackTrace(); + + } finally { + PostgresDBConnectionProvider.close(connection, preparedStatement, resultSet); + } + + return new User(); + } + +} + diff --git a/src/main/java/no/ntnu/idatx1005/demo/data/MyEntity.java b/src/main/java/no/ntnu/idatx1005/demo/data/MyEntity.java new file mode 100644 index 0000000..270c859 --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/data/MyEntity.java @@ -0,0 +1,37 @@ +package no.ntnu.idatx1005.demo.data; + +import java.util.Date; +import java.util.List; + +/** + * This is just a simple Java-bean + * @author nilstes + */ +public class MyEntity { + private String id; + private String name; + + public MyEntity() { + } + + public MyEntity(String id, String name) { + this.id = id; + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } +} diff --git a/src/main/java/no/ntnu/idatx1005/demo/data/User.java b/src/main/java/no/ntnu/idatx1005/demo/data/User.java new file mode 100644 index 0000000..cfe888d --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/data/User.java @@ -0,0 +1,45 @@ +package no.ntnu.idatx1005.demo.data; + + +import java.util.UUID; + +/** + * Class for the User object as saved in database + */ +public class User { + private UUID userid; + private String username; + private String password; + + public User(){} + + public User(UUID userId, String username, String password){ + this.userid = userId; + this.username = username; + this.password = password; + } + + public UUID getUserid() { + return userid; + } + + public void setUserid(UUID userid) { + this.userid = userid; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/src/main/java/no/ntnu/idatx1005/demo/repo/MyEntityRepo.java b/src/main/java/no/ntnu/idatx1005/demo/repo/MyEntityRepo.java new file mode 100644 index 0000000..255601a --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/repo/MyEntityRepo.java @@ -0,0 +1,46 @@ +package no.ntnu.idatx1005.demo.repo; + +import no.ntnu.idatx1005.demo.data.MyEntity; + +import java.util.Arrays; +import java.util.List; + +/** + * Repository for the MyEntity-entity + * + * @author nilstes + */ +public class MyEntityRepo { + + /** + * Get object with given id + * + * @param id the entity id + * @return an instance of MyEntity + */ + public MyEntity getMyEntity(String id) { + // Get connection (maybe use pool?) + // Do some SQL + // Return som real data + + return new MyEntity("id", "name"); + } + + public List findMyEntities(String someParameter) { + // Get connection (maybe use pool?) + // Do some SQL + // Return som real data + + return Arrays.asList(new MyEntity("id1", "name1"), new MyEntity("id2", "name2")); + } + + public void addMyEntity(MyEntity obj) { + // Get connection (maybe use pool?) + // Do some SQL + } + + public void deleteMyEntity(String id) { + // Get connection (maybe use pool?) + // Do some SQL + } + } diff --git a/src/main/java/no/ntnu/idatx1005/demo/view/MyWindow.java b/src/main/java/no/ntnu/idatx1005/demo/view/MyWindow.java new file mode 100644 index 0000000..980b21b --- /dev/null +++ b/src/main/java/no/ntnu/idatx1005/demo/view/MyWindow.java @@ -0,0 +1,45 @@ +package no.ntnu.idatx1005.demo.view; + +import no.ntnu.idatx1005.demo.dao.PostgresDBConnectionProvider; +import no.ntnu.idatx1005.demo.dao.UserDAO; +import no.ntnu.idatx1005.demo.data.User; + +import java.awt.*; +import java.util.Random; +import java.util.UUID; +import javax.swing.*; + +/** + * Main window for my application! + * + * @author nilstes + */ +public class MyWindow extends JFrame { + + /** + * Constructor for window + * + * @param title Title ow the window + * @see Image + */ + public MyWindow(String title) { + super(title); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + setLayout(new GridLayout(10, 10, 1, 1)); + + + // This piece of code is just for testing the database connection + // First we create a user and add it to the database + // Then we get all users from the database and print them to the window + UserDAO userDao = new UserDAO(PostgresDBConnectionProvider.instance()); + userDao.addUser(new User(UUID.randomUUID(), "user " + new Random().nextInt(1000), "1234")); + java.util.List users = userDao.getUsers(); + for (User user : users) { + add(new JLabel(user.getUsername())); + } + + setPreferredSize(new Dimension(400, 300)); + setLocationRelativeTo(null); + pack(); + } +} diff --git a/src/main/resources/db b/src/main/resources/db new file mode 100644 index 0000000..e69de29 diff --git a/src/test/java/no/ntnu/idatx1005/demo/dao/DatabaseTest.java b/src/test/java/no/ntnu/idatx1005/demo/dao/DatabaseTest.java new file mode 100644 index 0000000..f0e0e7e --- /dev/null +++ b/src/test/java/no/ntnu/idatx1005/demo/dao/DatabaseTest.java @@ -0,0 +1,36 @@ +package no.ntnu.idatx1005.demo.dao; + +import java.sql.*; + +public class DatabaseTest { + public static void main(String[] args) throws ClassNotFoundException { + try { + String jdbcUrl = "jdbc:postgresql://localhost:5432/idatt1005-db"; + String username = "idatt1005user"; + String password = "idatt1005password"; + + // Register DB driver + Class.forName("org.postgresql.Driver"); + + // Connect to the DB + Connection connection = null; + connection = DriverManager.getConnection(jdbcUrl, username, password); + + // Perform DB operations + Statement statement = connection.createStatement(); + String sqlQuery = "SELECT * FROM userinfo"; + ResultSet resultSet = statement.executeQuery(sqlQuery); + while (resultSet.next()) + { + System.out.println("ID:" + resultSet.getString("userId")); + System.out.println("username:" + resultSet.getString("username")); + System.out.println("password:" + resultSet.getString("password")); + } + + // Close the connection + connection.close(); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/test/java/no/ntnu/idatx1005/demo/repo/MyEntityRepoTest.java b/src/test/java/no/ntnu/idatx1005/demo/repo/MyEntityRepoTest.java new file mode 100644 index 0000000..5f5f61e --- /dev/null +++ b/src/test/java/no/ntnu/idatx1005/demo/repo/MyEntityRepoTest.java @@ -0,0 +1,25 @@ +package no.ntnu.idatx1005.demo.repo; + +import no.ntnu.idatx1005.demo.data.MyEntity; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MyEntityRepoTest { + + @Test + public void testThatgetMyEntityMethodReturnAnEntiryWithCorrectName() { + MyEntity e = new MyEntityRepo().getMyEntity("id"); + assertEquals(e.getName(), "name"); + } + + + /** + @Test + public void testfindMyEntitiesMethodReturnAListOf2Entities() { + List e = new MyEntityRepo().findMyEntities("id"); + assertEquals(e.size(), 2); + } + */ + +} \ No newline at end of file diff --git a/src/test/resources/testdb b/src/test/resources/testdb new file mode 100644 index 0000000..e69de29