Skip to content
Draft
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
**/gradlew.bat
/local.properties
**/.idea
**/venv
# **/.idea/caches
# **/.idea/libraries
# **/.idea/modules.xml
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ static public ServerApiStorage getInstance() {
* </ol>
*/
private ServerApiStorage() {
serverHost = "192.168.0.102";/*"localhost"*/;
clientHost = "192.168.0.102"/*"localhost"*//*"10.0.2.2"*/; // emulators
serverHost = "192.168.43.221";/*"localhost"*/;
clientHost = "192.168.43.221"/*"localhost"*//*"10.0.2.2"*/; // emulators
// port is common for both client and server
port = 50051/*8080*/;
}
Expand Down
5 changes: 5 additions & 0 deletions migrations/initialization.down.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
DROP TABLE IF EXISTS game_session_tokens;
DROP TABLE IF EXISTS jwt_tokens;
DROP TABLE IF EXISTS users;

DROP TABLE IF EXISTS protection_walls CASCADE;
DROP TABLE IF EXISTS protection_wall_states CASCADE;
DROP TABLE IF EXISTS towers CASCADE;
DROP TABLE IF EXISTS positions CASCADE;
58 changes: 56 additions & 2 deletions migrations/initialization.up.sql
Original file line number Diff line number Diff line change
@@ -1,19 +1,73 @@
---- GAME AUTH-RELATED TABLES ----

-- Create user table
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
);


-- Create JWT tokens table
CREATE TABLE IF NOT EXISTS jwt_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER UNIQUE REFERENCES users(id),
token VARCHAR(255) NOT NULL
);

-- Create game session tokens table
CREATE TABLE IF NOT EXISTS game_session_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER UNIQUE REFERENCES users(id),
token VARCHAR(255) NOT NULL
);
);

---- GAME MODELS TABLES ----

-- Create positions table
CREATE TABLE IF NOT EXISTS positions (
id SERIAL PRIMARY KEY,
x DOUBLE PRECISION NOT NULL,
y DOUBLE PRECISION NOT NULL,
tower_id INT
);

-- Create towers table
CREATE TABLE IF NOT EXISTS towers (
id SERIAL PRIMARY KEY,
position_id INT REFERENCES positions(id) NOT NULL,
owner_id INT REFERENCES users(id) DEFAULT NULL,
owner_username TEXT DEFAULT NULL,
last_protection_wall_modification_timestamp TIMESTAMP DEFAULT NULL,
is_under_protection_walls_installation BOOLEAN DEFAULT false NOT NULL,
is_under_capture_lock BOOLEAN DEFAULT false NOT NULL,
is_under_attack BOOLEAN DEFAULT false NOT NULL
);

-- Alter positions table to add constaint to tower_id field
ALTER TABLE positions
ADD CONSTRAINT fk_positions_towers
FOREIGN KEY (tower_id) REFERENCES towers(id)
DEFERRABLE INITIALLY DEFERRED;


-- Create protection wall states table
CREATE TABLE protection_wall_states (
id SERIAL PRIMARY KEY,
broken BOOLEAN DEFAULT false NOT NULL,
enchanted BOOLEAN DEFAULT false NOT NULL,
protection_wall_id INT
);

-- Create protection walls table
CREATE TABLE IF NOT EXISTS protection_walls (
id SERIAL PRIMARY KEY,
tower_id INT REFERENCES towers(id) NOT NULL,
state_id INT REFERENCES protection_wall_states(id) NOT NULL
);

-- Alter protection_wall_states table to add constaint to protection_wall_id field
ALTER TABLE protection_wall_states
ADD CONSTRAINT fk_protection_wall_states_protection_walls
FOREIGN KEY (protection_wall_id) REFERENCES protection_walls(id)
DEFERRABLE INITIALLY DEFERRED;
93 changes: 93 additions & 0 deletions scripts/init.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import sys
import json
import psycopg2


def main(filepath):
with open(filepath) as file:
data = json.load(file)


# Extract connection details
connection_details = data['connection']

host = connection_details['host']
port = connection_details['port']
database = connection_details['database']
username = connection_details['username']
password = connection_details['password']

print("Connecting to database...")

# Connect to the database
connection = psycopg2.connect(
host=host,
port=port,
database=database,
user=username,
password=password
)
cursor = connection.cursor()

print("Connection established: host=" + host +
", port=" + port + ", database=" +
database + ", username=" +
username + ", password=" + password)

# Iterate over towers
towers = data['towers']

for tower_data in towers:
position = tower_data['position']
x = position['x']
y = position['y']

# Insert position into database
cursor.execute("INSERT INTO positions(x, y) VALUES (%s, %s) RETURNING id", (x, y))
position_id = cursor.fetchone()[0]

# Insert tower into the database
cursor.execute("INSERT INTO towers(position_id) VALUES (%s) RETURNING id", (position_id,))
tower_id = cursor.fetchone()[0]

# Update tower id of position in database
cursor.execute("UPDATE positions SET tower_id = %s WHERE id = %s", (tower_id, position_id))

print("Tower with id " + str(tower_id) + " saved")

# Store protection walls of tower
protection_walls = tower_data['protectionWalls']
for protection_wall_data in protection_walls:
state = protection_wall_data['state']
broken = state['broken']
enchanted = state['enchanted']

# Insert protection wall state into database
cursor.execute("INSERT INTO protection_wall_states(broken, enchanted) VALUES (%s, %s) RETURNING id", (broken, enchanted))
protection_wall_state_id = cursor.fetchone()[0]

# Insert protection wall into the database
cursor.execute("INSERT INTO protection_walls(tower_id, state_id) VALUES (%s, %s) RETURNING id", (tower_id, protection_wall_state_id))
protection_wall_id = cursor.fetchone()[0]

# Update protection wall id of protection wall state in database
cursor.execute("UPDATE protection_wall_states SET protection_wall_id = %s WHERE id = %s", (protection_wall_id, protection_wall_state_id))
print(str(len(protection_walls)) + " protection walls of tower with id " + str(tower_id) + " saved")


print("Committing...")
# Commit the changes and close the connection
connection.commit()
cursor.close()
connection.close()
print("====== Success! ======")



arguments = sys.argv[1:]

if (len(arguments) == 1):
filepath = arguments[0]
main(filepath)
else:
raise RuntimeError("Expected json filepath. Got: " + arguments)
13 changes: 0 additions & 13 deletions server/app/src/main/java/components/db/dao/UsersDao.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@


public class UsersDao {
public record UserDto(@NonNull String email, @NonNull String username, @NonNull String password) {}

private static final Logger logger = Logger.getLogger(UsersDao.class.getName());

public void save(User user) {
Expand All @@ -38,17 +36,6 @@ public void save(User user) {
}
}

public void updateUserRecord (User user) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
User newUser = session.get(User.class, user.getId());//?
newUser = user;
session.merge(newUser);
transaction.commit();
session.close();
logger.log(Level.INFO, "User is updated");
}

public Optional<User> findByEmail(String email) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
String queryString = "SELECT u FROM User u WHERE u.email = :email";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package components.db.dao.game;

import components.db.HibernateUtil;
import components.db.models.game.PositionModel;
import jakarta.persistence.RollbackException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.Optional;
import java.util.logging.Logger;

public class PositionModelsDao {
private static final Logger logger = Logger.getLogger(PositionModelsDao.class.getName());

public void save(PositionModel position) throws HibernateException {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// save user
session.persist(position);
transaction.commit();
logger.info("Position: " + position + " saved in db");
}
catch (RollbackException err) {
assert transaction != null;
transaction.rollback();
throw err;
}
}

public Optional<PositionModel> findByTowerId(int towerId) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
String queryString = "SELECT p FROM PositionModel p WHERE p.tower.id = :towerId";
Query<PositionModel> query = session.createQuery(queryString, PositionModel.class);
query.setParameter("towerId", towerId);

PositionModel position = query.uniqueResult();

if (position != null) {
logger.info("Found position: " + position);
return Optional.of(position);
}
else {
logger.info("No position associated with tower id " + towerId + " exists");
return Optional.empty();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package components.db.dao.game;

import components.db.HibernateUtil;
import components.db.models.game.PositionModel;
import components.db.models.game.ProtectionWallModel;
import jakarta.persistence.RollbackException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.Optional;
import java.util.logging.Logger;

public class ProtectionWallModelsDao {
private static final Logger logger = Logger.getLogger(ProtectionWallModelsDao.class.getName());

public void save(ProtectionWallModel protectionWall) throws HibernateException {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// save user
session.persist(protectionWall);
transaction.commit();
logger.info("Protection wall: " + protectionWall + " saved in db");
}
catch (RollbackException err) {
assert transaction != null;
transaction.rollback();
throw err;
}
}

public Optional<ProtectionWallModel> findByTowerId(int towerId) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
String queryString = "SELECT w FROM ProtectionWallModel w WHERE w.tower.id = :towerId";
Query<ProtectionWallModel> query = session.createQuery(queryString, ProtectionWallModel.class);
query.setParameter("towerId", towerId);

ProtectionWallModel protectionWall = query.uniqueResult();

if (protectionWall != null) {
logger.info("Found protection wall: " + protectionWall);
return Optional.of(protectionWall);
}
else {
logger.info("No protection wall associated with tower id " + towerId + " exists");
return Optional.empty();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package components.db.dao.game;

import components.db.HibernateUtil;
import components.db.models.game.PositionModel;
import components.db.models.game.ProtectionWallStateModel;
import jakarta.persistence.RollbackException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.Optional;
import java.util.logging.Logger;

public class ProtectionWallStateModelsDao {
private static final Logger logger = Logger.getLogger(ProtectionWallStateModelsDao.class.getName());

public void save(ProtectionWallStateModel wallState) throws HibernateException {
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
transaction = session.beginTransaction();
// save user
session.persist(wallState);
transaction.commit();
logger.info("Wall state: " + wallState + " saved in db");
}
catch (RollbackException err) {
assert transaction != null;
transaction.rollback();
throw err;
}
}

public Optional<ProtectionWallStateModel> findByProtectionWallId(int protectionWallId) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
String queryString = "SELECT s FROM ProtectionWallStateModel s WHERE s.protectionWall.id = :protectionWallId";
Query<ProtectionWallStateModel> query = session.createQuery(queryString, ProtectionWallStateModel.class);
query.setParameter("protectionWallId", protectionWallId);

ProtectionWallStateModel wallState = query.uniqueResult();

if (wallState != null) {
logger.info("Found wall state: " + wallState);
return Optional.of(wallState);
}
else {
logger.info("No state associated with protection wall id " + protectionWallId + " exists");
return Optional.empty();
}
}
}
}
Loading