diff --git a/.gitignore b/.gitignore index 178135c..7ab6725 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /dist/ +/nbproject/private/ +/build/ diff --git a/FUNET.iml b/FUNET.iml new file mode 100644 index 0000000..70b61e7 --- /dev/null +++ b/FUNET.iml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/database/FUNET.sql b/database/FUNET.sql index e1e3573..7252c59 100644 --- a/database/FUNET.sql +++ b/database/FUNET.sql @@ -1,211 +1,436 @@ -CREATE DATABASE FUNET; - -GO -USE FUNET; - -GO -DROP TABLE IF EXISTS friendship; -DROP TABLE IF EXISTS message; -DROP TABLE IF EXISTS comment; -DROP TABLE IF EXISTS post_like; -DROP TABLE IF EXISTS post; -DROP TABLE IF EXISTS conversation_member; -DROP TABLE IF EXISTS userAccount; -DROP TABLE IF EXISTS conversation; -drop procedure if exists checkDuplicateEmail -drop procedure if exists registerUser -drop procedure if exists getAllFriends - -GO -CREATE TABLE userAccount ( - user_id INT IDENTITY(1,1) PRIMARY KEY, - first_name NVARCHAR(50) NOT NULL, - last_name NVARCHAR(50) NOT NULL, - password NVARCHAR(MAX) NULL, - email VARCHAR(70) NOT NULL UNIQUE, - profile_pic VARCHAR(max) NOT NULL, - role VARCHAR(20) NOT NULL, - is_banned BIT NOT NULL -); - -GO -CREATE TABLE friendship ( - friendship_id INT IDENTITY(1,1) PRIMARY KEY, - sender INT, - receiver INT, - status nvarchar(10) NOT NULL, - CONSTRAINT fk_sender FOREIGN KEY (sender) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_receiver FOREIGN KEY (receiver) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -GO -CREATE TABLE post ( - post_id INT IDENTITY(1,1) PRIMARY KEY, - user_id INT NOT NULL, - body NVARCHAR(200), - image_path NVARCHAR(max), - post_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - like_count INT not null default 0, - CONSTRAINT fk_post_user FOREIGN KEY (user_id) REFERENCES userAccount (user_id) ON DELETE CASCADE ON UPDATE CASCADE -); - -GO -CREATE TABLE post_like ( - like_id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, - user_id INT NOT NULL, - post_id INT NOT NULL, - like_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT fk_like_user FOREIGN KEY (user_id) REFERENCES userAccount (user_id), - CONSTRAINT fk_like_post FOREIGN KEY (post_id) REFERENCES post(post_id) -); - -GO -CREATE TABLE comment ( - comment_id INT IDENTITY(1,1) PRIMARY KEY, - post_id INT NOT NULL, - user_id INT NOT NULL, - comment_text NVARCHAR(MAX) NOT NULL, - comment_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT fk_comment_post FOREIGN KEY (post_id) REFERENCES post (post_id) ON DELETE CASCADE, - CONSTRAINT fk_comment_user FOREIGN KEY (user_id) REFERENCES userAccount (user_id) -); - -GO -CREATE TABLE conversation ( - conversation_id INT PRIMARY KEY, - conversation_name NVARCHAR(50), - conversation_avater nvarchar(50) NOT NULL -); - -GO -CREATE TABLE message ( - message_id INT IDENTITY(1,1) PRIMARY KEY, - sender INT NOT NULL, - receiver INT, - conversation_id INT NOT NULL, - message_text NVARCHAR(400) NOT NULL, - message_type VARCHAR(40) NOT NULL, - sent_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (sender) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION, - FOREIGN KEY (receiver) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION, - FOREIGN KEY (conversation_id) REFERENCES conversation (conversation_id) ON DELETE NO ACTION ON UPDATE NO ACTION -); - -GO -CREATE TABLE conversation_member ( - is_admin BIT NOT NULL, - user_id INT, - conversation_id INT, - CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES userAccount(user_id), - CONSTRAINT fk_convesation FOREIGN KEY (conversation_id) REFERENCES conversation (conversation_id) ON DELETE NO ACTION ON UPDATE NO ACTION, - PRIMARY KEY (user_id, conversation_id) -) - -GO -CREATE PROCEDURE registerUser - @first_name varchar(20), - @last_name varchar(20), - @password varchar(20), - @email varchar(50) -AS - BEGIN TRANSACTION - - IF EXISTS ( - SELECT 1 - FROM userAccount - WHERE email = @email - ) - BEGIN - ROLLBACK TRANSACTION; - THROW 5000, 'Duplicated Email.', 1; - RETURN; - END - - INSERT INTO userAccount (first_name, last_name, password, email) - VALUES (@first_name, @last_name, @password, @email) - - COMMIT TRANSACTION; - -GO -CREATE PROCEDURE getAllFriends - @userId INT -AS -BEGIN - SELECT u.user_id, u.first_name, u.last_name, u.profile_pic, u.role, u.is_banned, f.status - FROM userAccount u - INNER JOIN friendship f ON - (f.sender = u.user_id AND f.receiver = @userId) - OR (f.receiver = u.user_id AND f.sender = @userId) - WHERE f.status = 'accepted'; -END; - -insert into userAccount values ('Nguyen', 'Tuan' , '123', 'anhtuan123@gmail.com', 'default_avt.jpg', 'student', 'false') -insert into userAccount values ('Ha', 'Phan', '123', 'haphan123@gmail.com', 'default_avt.jpg', 'staft', 'false') -insert into userAccount values ('Thanh', 'Tung', '123', 'thanhtung123@gmail.com', 'default_avt.jpg', 'student', 'false') -insert into userAccount values ('vua', 'ga', '123', 'vuaga1260@gmail.com', 'default_avt.jpg', 'student', 'false') - - - -Go -Select * from userAccount - -EXEC getAllFriends 1; - -CREATE TABLE product ( - product_id INT IDENTITY(1,1) PRIMARY KEY, - user_id INT NOT NULL, - product_name NVARCHAR(255) NOT NULL, - product_description NVARCHAR(500), -- Điều chỉnh độ dài nếu cần - product_img text NOT NULL, - product_tag NVARCHAR(255) NOT NULL, - publish_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - price DECIMAL(10, 2) NOT NULL, -- Điều chỉnh kiểu dữ liệu để biểu diễn giá - CONSTRAINT fk_product_user_id FOREIGN KEY (user_id) REFERENCES userAccount(user_id) -); -GO - -CREATE TABLE learningmaterial ( - learningmaterial_id INT IDENTITY(1,1) PRIMARY KEY, - user_id INT NOT NULL, - learningmaterial_name NVARCHAR(255) NOT NULL, - learningmaterial_description NVARCHAR(500), -- Tăng độ dài mô tả nếu cần - learningmaterial_img NVARCHAR(MAX) NOT NULL, -- Change to NVARCHAR(MAX) - learningmaterial_context NVARCHAR(MAX) NOT NULL, -- Change to NVARCHAR(MAX) - subject_code NVARCHAR(7) NOT NULL, - publish_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Thêm giá trị mặc định - review NVARCHAR(MAX), -- Thay đổi kiểu dữ liệu cho phù hợp - CONSTRAINT fk_learningmaterial_user_id FOREIGN KEY (user_id) REFERENCES userAccount(user_id) -); -GO - -INSERT INTO learningmaterial (user_id, learningmaterial_name, learningmaterial_description, learningmaterial_img, learningmaterial_context, subject_code, review) -VALUES -(1, 'Introduction to Programming', 'A comprehensive guide to programming concepts for beginners.', 'assets/product/item.png', 'assets/leaningMaterial/SWR302_LAB.docx', 'CS101', 'Great resource for beginners.'), -(3, 'Data Structures and Algorithms', 'Understand the key data structures and algorithms used in computer science.', 'assets/product/item.png', 'assets/leaningMaterial/SWR302_LAB.docx', 'CS404', 'Excellent for interview preparation.'), -(2, 'Machine Learning Basics', 'An introduction to the concepts of machine learning and its applications.', 'assets/product/item.png', 'assets/leaningMaterial/SWR302_LAB.docx', 'CS505', 'Great starting point for ML enthusiasts.'); - -GO - -SELECT * FROM learningmaterial - -ALTER TABLE friendship DROP CONSTRAINT fk_sender; -ALTER TABLE friendship DROP CONSTRAINT fk_receiver; - -ALTER TABLE post DROP CONSTRAINT fk_post_user; - -ALTER TABLE post_like DROP CONSTRAINT fk_like_user; -ALTER TABLE post_like DROP CONSTRAINT fk_like_post; - -ALTER TABLE comment DROP CONSTRAINT fk_comment_user; -ALTER TABLE comment DROP CONSTRAINT fk_comment_post; - -ALTER TABLE message DROP CONSTRAINT fk_sender; -ALTER TABLE message DROP CONSTRAINT fk_receiver; -ALTER TABLE message DROP CONSTRAINT fk_conversation; - -ALTER TABLE conversation_member DROP CONSTRAINT fk_user_id; -ALTER TABLE conversation_member DROP CONSTRAINT fk_convesation; - -ALTER TABLE product DROP CONSTRAINT fk_product_user_id; - -ALTER TABLE learningmaterial DROP CONSTRAINT fk_learningmaterial_user_id; \ No newline at end of file + +CREATE DATABASE FUNET; + +GO +USE FUNET; + +GO +DROP TABLE IF EXISTS friendship; +DROP TABLE IF EXISTS comment; +DROP TABLE IF EXISTS post_like; +DROP TABLE IF EXISTS post_share; +DROP TABLE IF EXISTS post; +DROP TABLE IF EXISTS message; +DROP TABLE IF EXISTS conversation_users; +DROP TABLE IF EXISTS conversation; +DROP TABLE IF EXISTS categories; +DROP TABLE IF EXISTS game; +DROP TABLE IF EXISTS GameCategory; +DROP TABLE IF EXISTS categories; +DROP TABLE IF EXISTS learningmaterial; +DROP TABLE IF EXISTS conversation; +DROP TABLE IF EXISTS product; +DROP TABLE IF EXISTS UserActivityLog; +DROP TABLE IF EXISTS userAccount; +drop procedure if exists getAllFriends; +DROP TRIGGER IF EXISTS TR_Post_Activity; +DROP TRIGGER IF EXISTS TR_Comment_Activity; +DROP TRIGGER IF EXISTS TR_PostLike_Activity; + +GO +CREATE TABLE userAccount ( + user_id INT IDENTITY(1,1) PRIMARY KEY, + first_name NVARCHAR(50) NOT NULL, + last_name NVARCHAR(50) NOT NULL, + password VARCHAR(30) NULL, + email VARCHAR(70) NOT NULL UNIQUE, + profile_pic VARCHAR(max) NOT NULL, + role VARCHAR(20) NOT NULL, + user_introduce NVARCHAR(50), + is_banned BIT NOT NULL, + created_at DATE DEFAULT CAST(GETDATE() AS DATE) NOT NULL +); + + +GO +CREATE TABLE friendship ( + friendship_id INT IDENTITY(1,1) PRIMARY KEY, + sender INT, + receiver INT, + status nvarchar(10) NOT NULL, + CONSTRAINT fk_sender FOREIGN KEY (sender) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_receiver FOREIGN KEY (receiver) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +GO +CREATE TABLE post ( + post_id INT IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + body NVARCHAR(200), + image_path NVARCHAR(max), + post_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + like_count INT not null default 0, + is_shared BIT NOT NULL DEFAULT 0, + original_post_id INT NULL, + share_count INT NOT NULL DEFAULT 0, + privacy_mode NVARCHAR(10) NOT NULL DEFAULT 'friend', + FOREIGN KEY (user_id) REFERENCES userAccount (user_id), + type NVARCHAR(max) +); + +GO +CREATE TABLE post_like ( + like_id INT NOT NULL IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + post_id INT NOT NULL, + like_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT fk_like_user FOREIGN KEY (user_id) REFERENCES userAccount (user_id), + CONSTRAINT fk_like_post FOREIGN KEY (post_id) REFERENCES post(post_id) +); + +GO +CREATE TABLE comment ( + comment_id INT IDENTITY(1,1) PRIMARY KEY, + post_id INT NOT NULL, + user_id INT NOT NULL, + comment_text NVARCHAR(MAX) NOT NULL, + comment_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (post_id) REFERENCES post (post_id), + comment_image NVARCHAR(MAX), + FOREIGN KEY (user_id) REFERENCES userAccount (user_id) +); + +GO +CREATE TABLE conversation ( + conversation_id INT IDENTITY(1,1) PRIMARY KEY, + conversation_name NVARCHAR(50), + conversation_avatar nvarchar(200) NOT NULL +); + +GO +CREATE TABLE conversation_users ( + is_admin BIT NOT NULL, + user_id INT, + conversation_id INT, + FOREIGN KEY (user_id) REFERENCES userAccount(user_id), + FOREIGN KEY (conversation_id) REFERENCES conversation (conversation_id), + PRIMARY KEY (user_id, conversation_id) +); + +GO +CREATE TABLE message ( + message_id INT IDENTITY(1,1) PRIMARY KEY, + sender INT NOT NULL, + receiver INT, + conversation_id INT NOT NULL, + message_text NVARCHAR(400) NOT NULL, + message_type VARCHAR(40) NOT NULL, + sent_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (sender) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION, + FOREIGN KEY (receiver) REFERENCES userAccount (user_id) ON DELETE NO ACTION ON UPDATE NO ACTION, + FOREIGN KEY (conversation_id) REFERENCES conversation (conversation_id) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +GO +CREATE TABLE post_share ( + share_id INT IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + post_id INT NOT NULL, + share_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + like_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES userAccount (user_id), + FOREIGN KEY (post_id) REFERENCES post(post_id) +); + +GO +CREATE TABLE categories ( + tag_id INT PRIMARY KEY IDENTITY(1,1), + tag_name NVARCHAR(50) NOT NULL +); +go +CREATE TABLE GameCategory ( + CategoryID INT PRIMARY KEY IDENTITY(1,1), + CategoryName NVARCHAR(50) NOT NULL +); +GO +INSERT INTO GameCategory (CategoryName) VALUES +(N'Action'), +(N'Adventure'), +(N'Board game'), +(N'Card game'), +(N'Building'), +(N'Combat'); +GO + +GO +CREATE TABLE Game ( + GameID INT PRIMARY KEY, + GameName NVARCHAR(50) NOT NULL, + GameLink NVARCHAR(200), + Img NVARCHAR(200), + CategoryID INT, + FOREIGN KEY (CategoryID) REFERENCES GameCategory(CategoryID) +); + + +select * from Game +GO +INSERT INTO Game (GameID, GameName, GameLink,Img, CategoryID) VALUES +(1, N'Triple Cars', 'https://cdn.htmlgames.com/TripleCars/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128426/1_m5ce3b.jpg', 1), +(2, N'Pyramid Solitaire - Great Pyramid', 'https://cdn.htmlgames.com/PyramidSolitaire-GreatPyramid/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128429/2_hbckn7.jpg', 4), +(3, N'Sushi Master', 'https://cdn.htmlgames.com/SushiMasterMatch3/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128432/3_fejrwt.jpg' ,3), +(4, N'Goblin Run', 'https://cdn.htmlgames.com/GoblinRun/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128433/4_mwn2gs.jpg' ,1), +(5, N'Solitaire Collection 2', 'https://cdn.htmlgames.com/SolitaireCollection2/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128434/5_kqtfci.jpg' ,4), +(6, N'Escape Room - Home Escape', 'https://cdn.htmlgames.com/EscapeRoom-HomeEscape/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128436/6_jnwrix.jpg' ,2), +(7, N'Reach 7', 'https://cdn.htmlgames.com/Reach7/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128437/7_mnp4xu.jpg',3), +(8, N'Solitaire Collection', 'https://cdn.htmlgames.com/SolitaireCollection/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128440/8_zsb97b.jpg',4), +(9, N'2048 Billiards', 'https://cdn.htmlgames.com/2048Billiards/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128443/9_n0pe4j.jpg',3), +(10, N'Jungle Link', 'https://cdn.htmlgames.com/JungleLink/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128442/10_haa16t.jpg',2), +(11, N'The Watermelon Game', 'https://cdn.htmlgames.com/TheWatermelonGame/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128447/11_mfk2fp.png' ,5), +(12, N'Double Klondike', 'https://cdn.htmlgames.com/DoubleKlondike/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128446/12_chkpc8.png' ,4), +(13, N'Water Sort', 'https://cdn.htmlgames.com/WaterSort/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128451/13_ln7tcj.png',1), +(14, N'Jungle Sniper', 'https://cdn.htmlgames.com/JungleSniper/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128449/14_s56l3x.png',6), +(15, N'Kitty Mahjong', 'https://cdn.htmlgames.com/KittyMahjong/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128455/15_vzjess.png' ,6), +(16, N'Balloon Maze', 'https://cdn.htmlgames.com/BalloonMaze/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128456/16_duqruw.png' ,2), +(17, N'Mysterious Pirate Jewels 3', 'https://cdn.htmlgames.com/MysteriousPirateJewels3/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128453/17_urluf9.png' ,2), +(18, N'Aladdin Solitaire', 'https://cdn.htmlgames.com/AladdinSolitaire/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128463/18_linw8x.png' ,3), +(19, N'Tap It Away 3D', 'https://cdn.htmlgames.com/TapItAway3D/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128459/19_nbcgxt.png' ,5), +(20, N'Pyramid Solitaire - Ancient China', 'https://cdn.htmlgames.com/PyramidSolitaire-AncientChina/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128467/20_d8w2fu.png' ,2), +(21, N'Ninja Breakout', 'https://cdn.htmlgames.com/NinjaBreakout/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128462/21_atiu5f.png',6), +(22, N'Bubble Throw', 'https://cdn.htmlgames.com/BubbleThrow/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128473/22_tvl6jc.png',6), +(23, N'Freecell Extreme', 'https://cdn.htmlgames.com/FreecellExtreme/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128474/23_ardt0p.png',4), +(24, N'Connect the Dots', 'https://cdn.htmlgames.com/ConnectTheDots/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128466/24_szcuqa.png' ,5), +(25, N'Harbour Escape', 'https://cdn.htmlgames.com/HarbourEscape/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128476/25_nag1rk.png',1), +(26, N'Flower World 2', 'https://cdn.htmlgames.com/FlowerWorld2/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128478/26_hrruhx.png' ,1), +(27, N'Black and White Mahjong 3', 'https://cdn.htmlgames.com/BlackAndWhiteMahjong3/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128471/27_uimb29.png' ,3), +(28, N'Archery Training', 'https://cdn.htmlgames.com/ArcheryTraining/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128480/28_sdcsmp.png' ,6), +(29, N'Spooky Dimensions', 'https://cdn.htmlgames.com/SpookyDimensions/','https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128482/29_xpuh9w.png' ,5), +(30, N'Circus Match 3', 'https://cdn.htmlgames.com/CircusMatch3/', 'https://res.cloudinary.com/dxx8u5qnr/image/upload/v1730128484/30_s6hfa9.png',5); + + +go +select * from game + +CREATE TABLE UserActivityLog ( + log_id INT IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + activity_type VARCHAR(50) NOT NULL, + activity_details NVARCHAR(MAX), + post_id INT NULL, + comment_id INT NULL, + timestamp DATETIME DEFAULT GETDATE(), + FOREIGN KEY (user_id) REFERENCES userAccount(user_id), + FOREIGN KEY (post_id) REFERENCES post(post_id), + FOREIGN KEY (comment_id) REFERENCES comment(comment_id) +); +go +CREATE TRIGGER TR_Post_Activity +ON post +AFTER INSERT, UPDATE +AS +BEGIN + + INSERT INTO UserActivityLog (user_id, activity_type, activity_details, post_id) + SELECT + i.user_id, + 'POST_CREATED', + i.body, + i.post_id + FROM inserted i + WHERE NOT EXISTS (SELECT 1 FROM deleted); + + + INSERT INTO UserActivityLog (user_id, activity_type, activity_details, post_id) + SELECT + i.user_id, + 'POST_UPDATED', + 'Changed from: ' + ISNULL(d.body, 'empty') + ' to: ' + ISNULL(i.body, 'empty'), -- Show content change + i.post_id + FROM inserted i + INNER JOIN deleted d ON i.post_id = d.post_id; +END; + +go +CREATE TRIGGER TR_Comment_Activity +ON comment +AFTER INSERT, UPDATE +AS +BEGIN + + INSERT INTO UserActivityLog (user_id, activity_type, activity_details, post_id, comment_id) + SELECT + i.user_id, + 'COMMENT_CREATED', + i.comment_text, + i.post_id, + i.comment_id + FROM inserted i + WHERE NOT EXISTS (SELECT 1 FROM deleted); + + + INSERT INTO UserActivityLog (user_id, activity_type, activity_details, post_id, comment_id) + SELECT + i.user_id, + 'COMMENT_UPDATED', + 'Changed from: ' + ISNULL(d.comment_text, 'empty') + ' to: ' + ISNULL(i.comment_text, 'empty'), -- Show content change + i.post_id, + i.comment_id + FROM inserted i + INNER JOIN deleted d ON i.comment_id = d.comment_id; + + + +END; + + + +GO +CREATE TABLE product ( + product_id INT IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + product_name NVARCHAR(255) NOT NULL, + product_description NVARCHAR(500), + product_img text NOT NULL, + product_tag NVARCHAR(255) NOT NULL, + publish_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + price DECIMAL(10, 2) NOT NULL, + CONSTRAINT fk_product_user_id FOREIGN KEY (user_id) REFERENCES userAccount(user_id) +); +GO + +CREATE TABLE shoppingCart ( + cart_id INT IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + add_date DATETIME DEFAULT GETDATE(), +); +Go + +CREATE TABLE shoppingCartItem ( + item_id INT PRIMARY KEY IDENTITY(1,1), + cart_id INT NOT NULL, + product_id INT NOT NULL, + quantity INT NOT NULL CHECK (quantity > 0), + added_at DATETIME DEFAULT GETDATE(), + FOREIGN KEY (cart_id) REFERENCES ShoppingCart(cart_id), + FOREIGN KEY (product_id) REFERENCES Product(product_id) +) + +CREATE TABLE Orders ( + order_id INT primary key, + user_id INT NOT NULL, + cart_id INT NOT NULL, + total_amount DECIMAL(10, 2) NOT NULL, + order_status NVARCHAR(50) DEFAULT 'Pending', -- E.g., Pending, Shipped, Delivered + order_date DATETIME DEFAULT GETDATE(), + order_note NVARCHAR(MAX) NOT NULL, + shipping_address NVARCHAR(255) NOT NULL +); +GO + + +INSERT INTO ShoppingCart (user_id) +VALUES +(1), +(188); +GO + +INSERT INTO ShoppingCartItem (cart_id, product_id, quantity) +VALUES +(3, 6, 1), +(3, 7, 2), +(4, 8, 1); +GO + +INSERT INTO Orders (user_id, total_amount, order_status, shipping_address) +VALUES +(3, 1500.00, 'Pending', '123 Main St, City'); +GO + +INSERT INTO OrderDetails (order_id, product_id, quantity, price_per_unit) +VALUES +(1, 6, 1, 1200.00), -- 1 Laptop in Order ID 1 +(1, 7, 2, 150.00); -- 2 Headphones in Order ID 1 +GO + + +GO +CREATE TABLE learningmaterial ( + learningmaterial_id INT IDENTITY(1,1) PRIMARY KEY, + user_id INT NOT NULL, + learningmaterial_name NVARCHAR(255) NOT NULL, + learningmaterial_description NVARCHAR(500), + learningmaterial_context NVARCHAR(255) NOT NULL, + subject_code NVARCHAR(7) NOT NULL, + publish_date DATETIME2(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, -- Ensure millisecond precision + review NVARCHAR(MAX), + department_id INT NOT NULL, + CONSTRAINT fk_learningmaterial_user_id FOREIGN KEY (user_id) REFERENCES userAccount(user_id) +); +INSERT INTO learningmaterial (user_id, learningmaterial_name, learningmaterial_description, learningmaterial_context, subject_code, publish_date, review, department_id) VALUES +(1, 'Economics 101', 'Introduction to Economics', 'econ101.pdf', 'ECON101', GETDATE(), 'Great material for beginners', 1), +(2, 'Advanced IT', 'Deep dive into IT topics', 'adv_it.pdf', 'IT202', GETDATE(), 'In-depth and comprehensive', 2), +(3, 'Tourism Basics', 'Fundamentals of Tourism', 'tourism_basics.pdf', 'TOUR101', GETDATE(), 'Essential for tourism students', 3), +(4, 'Language Learning', 'Effective language learning techniques', 'lang_learning.pdf', 'LANG101', GETDATE(), 'Very helpful for language learners', 4); + + + +CREATE TABLE saved_post ( + user_id INT NOT NULL, + post_id INT NOT NULL, + PRIMARY KEY (user_id, post_id), + CONSTRAINT fk_saved_user FOREIGN KEY (user_id) REFERENCES userAccount(user_id), + CONSTRAINT fk_saved_post FOREIGN KEY (post_id) REFERENCES post(post_id) +); + + +GO +CREATE PROCEDURE getAllFriends + @userId INT +AS +BEGIN + SELECT u.user_id, u.first_name, u.last_name, u.profile_pic, u.role, u.is_banned, f.status + FROM userAccount u + INNER JOIN friendship f ON + (f.sender = u.user_id AND f.receiver = @userId) + OR (f.receiver = u.user_id AND f.sender = @userId) + WHERE f.status = 'accepted'; +END; + + +go + -- January +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserJan', 'LastnameJan', 'password', 'userjan@example.com', 'default_avt.jpg', 'student', 0, '2024-01-15'); + +-- February +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserFeb', 'LastnameFeb', 'password', 'userfeb@example.com', 'default_avt.jpg', 'student', 0, '2024-02-15'); + +-- March +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserMar', 'LastnameMar', 'password', 'usermar@example.com', 'default_avt.jpg', 'student', 0, '2024-03-15'); + +-- April +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserApr', 'LastnameApr', 'password', 'userapr@example.com', 'default_avt.jpg', 'student', 0, '2024-04-15'); + +-- May +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserMay', 'LastnameMay', 'password', 'usermay@example.com', 'default_avt.jpg', 'staff', 0, '2024-05-15'); + +-- June +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserJun', 'LastnameJun', 'password', 'userjun@example.com', 'default_avt.jpg', 'staff', 0, '2024-06-15'); + +-- July +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserJul', 'LastnameJul', 'password', 'userjul@example.com', 'default_avt.jpg', 'student', 0, '2024-07-15'); + +-- August +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserAug', 'LastnameAug', 'password', 'useraug@example.com', 'default_avt.jpg', 'staff', 0, '2024-08-15'); + +-- September +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserSep', 'LastnameSep', 'password', 'usersep@example.com', 'default_avt.jpg', 'student', 0, '2024-09-15'); + +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserOctgaaah', 'LastnameOct', 'password', 'useroct@exampddalems.com', 'default_avt.jpg', 'staff', 0, '2024-09-15'); + + +-- October +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserOct', 'LastnameOct', 'password', 'useroct@example.com', 'default_avt.jpg', 'staff', 0, '2024-10-15'); + +INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned, created_at) +VALUES ('UserOctgh', 'LastnameOct', 'password', 'useroct@examplems.com', 'default_avt.jpg', 'staff', 0, '2024-10-15'); diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml index e6235cf..c9e33e9 100644 --- a/nbproject/build-impl.xml +++ b/nbproject/build-impl.xml @@ -982,48 +982,84 @@ exists or setup the property manually. For example like this: - - - - - - - - - + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + - - - - - - - - - + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/build-impl.xml~ b/nbproject/build-impl.xml~ new file mode 100644 index 0000000..3170928 --- /dev/null +++ b/nbproject/build-impl.xml~ @@ -0,0 +1,1569 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set build.web.dir + Must set build.generated.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.war + + + + + + + + + +The Java EE server classpath is not correctly set up - server home directory is missing. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Dj2ee.server.home=<app_server_installation_directory> + + +The Java EE server classpath is not correctly set up. Your active server type is ${j2ee.server.type}. +Either open the project in the IDE and assign the server or setup the server classpath manually. +For example like this: + ant -Duser.properties.file=<path_to_property_file> (where you put the property "j2ee.platform.classpath" in a .properties file) +or ant -Dj2ee.platform.classpath=<server_classpath> (where no properties file is used) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +The libs.CopyLibs.classpath property is not set up. +This property must point to +org-netbeans-modules-java-j2seproject-copylibstask.jar file which is part +of NetBeans IDE installation and is usually located at +<netbeans_installation>/java<version>/ant/extra folder. +Either open the project in the IDE and make sure CopyLibs library +exists or setup the property manually. For example like this: + ant -Dlibs.CopyLibs.classpath=a/path/to/org-netbeans-modules-java-j2seproject-copylibstask.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.jsp.includes + + + + + + + + + + + + + + + + + + + + + + + + + + Must select a file in the IDE or set jsp.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +<<<<<<< HEAD + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +======= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +>>>>>>> origin/main + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Browser not found, cannot launch the deployed application. Try to set the BROWSER environment variable. + + + Launching ${browse.url} + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties index 535ca5c..65c1651 100644 --- a/nbproject/genfiles.properties +++ b/nbproject/genfiles.properties @@ -1,8 +1,19 @@ -build.xml.data.CRC32=bc5fa736 +<<<<<<< HEAD +build.xml.data.CRC32=80e5c640 build.xml.script.CRC32=3e217ebe build.xml.stylesheet.CRC32=1707db4f@1.99.0.1 # This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. # Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. -nbproject/build-impl.xml.data.CRC32=bc5fa736 -nbproject/build-impl.xml.script.CRC32=05bf5cba +nbproject/build-impl.xml.data.CRC32=80e5c640 +nbproject/build-impl.xml.script.CRC32=f80a9f5c nbproject/build-impl.xml.stylesheet.CRC32=334708a0@1.99.0.1 +======= +build.xml.data.CRC32=2bac40e6 +build.xml.script.CRC32=3e217ebe +build.xml.stylesheet.CRC32=1707db4f@1.97.0.1 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=2bac40e6 +nbproject/build-impl.xml.script.CRC32=6d6280d3 +nbproject/build-impl.xml.stylesheet.CRC32=334708a0@1.97.0.1 +>>>>>>> origin/main diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties index 4dfeb13..873004e 100644 --- a/nbproject/private/private.properties +++ b/nbproject/private/private.properties @@ -1,7 +1,7 @@ -deploy.ant.properties.file=C:\\Users\\ADMIN\\AppData\\Roaming\\NetBeans\\23\\tomcat101.properties -j2ee.server.home=F:/Tomcat/apache-tomcat-10.1.23-windows-x64/apache-tomcat-10.1.23 -j2ee.server.instance=tomcat101:home=F:\\Tomcat\\apache-tomcat-10.1.23-windows-x64\\apache-tomcat-10.1.23 -javac.debug=true -javadoc.preview=true -selected.browser=default -user.properties.file=C:\\Users\\ADMIN\\AppData\\Roaming\\NetBeans\\23\\build.properties +deploy.ant.properties.file=C:\\Users\\OS\\AppData\\Roaming\\NetBeans\\17\\tomcat101.properties +j2ee.server.home=C:/Program Files/Apache Software Foundation/Tomcat 10.1 +j2ee.server.instance=tomcat101:home=C:\\Program Files\\Apache Software Foundation\\Tomcat 10.1 +javac.debug=true +javadoc.preview=true +selected.browser=default +user.properties.file=C:\\Users\\OS\\AppData\\Roaming\\NetBeans\\17\\build.properties diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml index 84e7071..bdd494c 100644 --- a/nbproject/private/private.xml +++ b/nbproject/private/private.xml @@ -1,22 +1,39 @@ - - - src/java/controller/marketLink.java - - - 19 - - - - + - file:/F:/New%20folder/FUNET3/src/java/controller/notificationServlet.java - file:/F:/New%20folder/FUNET3/web/vnpay_return.jsp - file:/F:/New%20folder/FUNET3/src/java/controller/SearchProductServlet.java - file:/F:/New%20folder/FUNET3/src/java/controller/marketLink.java - file:/F:/New%20folder/FUNET3/web/WEB-INF/marketNotification.jsp + file:/E:/FUNET/FUNET/web/WEB-INF/friendRequest.jsp + file:/E:/FUNET/FUNET/src/java/model/Message.java + file:/E:/FUNET/FUNET/web/WEB-INF/verify.jsp + file:/E:/FUNET/FUNET/src/java/model/Comment.java + file:/E:/FUNET/FUNET/src/java/controller/VerifyServlet.java + file:/E:/FUNET/FUNET/src/java/websockets/MessageEncoder.java + file:/E:/FUNET/FUNET/web/assets/css/search.css + file:/E:/FUNET/FUNET/src/java/controller/ChatController.java + file:/E:/FUNET/FUNET/web/assets/css/profile.css + file:/E:/FUNET/FUNET/src/java/controller/signupServlet.java + file:/E:/FUNET/FUNET/src/java/dao/MessageDao.java + file:/E:/FUNET/FUNET/web/assets/css/home.css + file:/E:/FUNET/FUNET/src/java/websockets/MessageDecoder.java + file:/E:/FUNET/FUNET/web/assets/js/likeButton.js + file:/E:/FUNET/FUNET/web/META-INF/context.xml + file:/E:/FUNET/FUNET/src/java/services/ChatService.java + file:/E:/FUNET/FUNET/src/java/controller/changeAvatarServlet.java + file:/E:/FUNET/FUNET/src/java/controller/loginServlet.java + file:/E:/FUNET/FUNET/src/java/controller/postServlet.java + file:/E:/FUNET/FUNET/web/assets/js/bootstrap.min.js + file:/E:/FUNET/FUNET/src/java/controller/userpageServlet.java + file:/E:/FUNET/FUNET/web/WEB-INF/setting.jsp + file:/E:/FUNET/FUNET/src/java/websockets/ChatWebsocket.java + file:/E:/FUNET/FUNET/src/java/controller/settingServlet.java + file:/E:/FUNET/FUNET/web/assets/css/test.css + file:/E:/FUNET/FUNET/web/WEB-INF/chatbox.jsp + file:/E:/FUNET/FUNET/src/java/util/sqlConnect.java + file:/E:/FUNET/FUNET/web/assets/js/likeButton.js + file:/E:/FUNET/FUNET/web/WEB-INF/chatbox.jsp + file:/E:/FUNET/FUNET/src/java/controller/postServlet.java + file:/E:/FUNET/FUNET/web/WEB-INF/home.jsp diff --git a/nbproject/project.properties b/nbproject/project.properties index 34577b8..a4dd6f4 100644 --- a/nbproject/project.properties +++ b/nbproject/project.properties @@ -1,3 +1,4 @@ +<<<<<<< HEAD annotation.processing.enabled=true annotation.processing.enabled.in.editor=true annotation.processing.processors.list= @@ -26,14 +27,28 @@ dist.ear.war=${dist.dir}/${war.ear.name} dist.javadoc.dir=${dist.dir}/javadoc dist.war=${dist.dir}/${war.name} excludes= +file.reference.cloudinary-core-1.33.0.jar=web\\assets\\library\\Cloudinary\\cloudinary-core-1.33.0.jar +file.reference.cloudinary-http44-1.39.0.jar=web\\assets\\library\\Cloudinary\\cloudinary-http44-1.39.0.jar +file.reference.commons-codec-1.17.1.jar=web\\assets\\library\\Cloudinary\\commons-codec-1.17.1.jar +file.reference.commons-fileupload-1.5.jar=web\\assets\\DropBox\\commons-fileupload-1.5.jar +file.reference.commons-io-2.11.0.jar=web\\assets\\DropBox\\commons-io-2.11.0.jar +file.reference.commons-io-2.17.0.jar=web\\assets\\library\\Cloudinary\\commons-io-2.17.0.jar file.reference.commons-logging-1.2.jar=web/assets/library/commons-logging-1.2.jar +file.reference.commons-logging-1.2.jar-1=web\\assets\\library\\Cloudinary\\commons-logging-1.2.jar +file.reference.dotenv-java-3.0.2.jar=web\\assets\\library\\Cloudinary\\dotenv-java-3.0.2.jar +file.reference.dropbox-core-sdk-5.4.4.jar=web\\assets\\DropBox\\dropbox-core-sdk-5.4.4.jar file.reference.fluent-hc-4.5.5.jar=web/assets/library/fluent-hc-4.5.5.jar file.reference.gson-2.10.1.jar=web/assets/library/gson-2.10.1.jar -file.reference.gson-2.3.1.jar=web\\assets\\gson-2.3.1.jar +file.reference.httpclient-4.5.14.jar=web\\assets\\library\\Cloudinary\\httpclient-4.5.14.jar file.reference.httpclient-4.5.5.jar=web/assets/library/httpclient-4.5.5.jar +file.reference.httpcore-4.4.16.jar=web\\assets\\library\\Cloudinary\\httpcore-4.4.16.jar file.reference.httpcore-4.4.9.jar=web/assets/library/httpcore-4.4.9.jar +file.reference.httpmime-4.5.14.jar=web\\assets\\library\\Cloudinary\\httpmime-4.5.14.jar +file.reference.jackson-annotations-2.15.2.jar=web\\assets\\DropBox\\jackson-annotations-2.15.2.jar file.reference.jackson-annotations-2.17.2.jar=web\\assets\\library\\jackson-annotations-2.17.2.jar +file.reference.jackson-core-2.15.2.jar=web\\assets\\DropBox\\jackson-core-2.15.2.jar file.reference.jackson-core-2.17.2.jar=web\\assets\\library\\jackson-core-2.17.2.jar +file.reference.jackson-databind-2.15.2.jar=web\\assets\\DropBox\\jackson-databind-2.15.2.jar file.reference.jackson-databind-2.17.2.jar=web\\assets\\library\\jackson-databind-2.17.2.jar file.reference.jakarta.activation-api-2.1.3.jar=web/assets/library/jakarta.activation-api-2.1.3.jar file.reference.jakarta.json-api-2.1.3.jar=web/assets/library/jakarta.json-api-2.1.3.jar @@ -43,14 +58,18 @@ file.reference.jakarta.servlet.jsp.jstl-api-3.0.0.jar=web/assets/library/jakarta file.reference.jakarta.websocket-api-2.2.0.jar=web/assets/library/jakarta.websocket-api-2.2.0.jar file.reference.jakarta.websocket-client-api-2.2.0.jar=web/assets/library/jakarta.websocket-client-api-2.2.0.jar file.reference.javaee-api-7.0.jar=web/assets/library/javaee-api-7.0.jar +file.reference.javax.servlet-api-4.0.1.jar=web\\assets\\DropBox\\javax.servlet-api-4.0.1.jar +file.reference.javax.servlet.jsp-api-2.3.3.jar=web\\assets\\DropBox\\javax.servlet.jsp-api-2.3.3.jar file.reference.json-20240303.jar=web/assets/library/json-20240303.jar file.reference.mssql-jdbc-12.6.1.jre11.jar=web/assets/library/Microsoft_JDBC_12.6/mssql-jdbc-12.6.1.jre11.jar +file.reference.slf4j-api-2.0.7.jar=web\\assets\\DropBox\\slf4j-api-2.0.7.jar +file.reference.slf4j-simple-2.0.7.jar=web\\assets\\DropBox\\slf4j-simple-2.0.7.jar includes=** j2ee.compile.on.save=true j2ee.copy.static.files.on.save=true j2ee.deploy.on.save=true j2ee.platform=10-web -j2ee.platform.classpath=${j2ee.server.home}/bin/tomcat-juli.jar:${j2ee.server.home}/lib/annotations-api.jar:${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/catalina-ssi.jar:${j2ee.server.home}/lib/catalina-storeconfig.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/ecj-4.27.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/jakartaee-migration-1.0.8-shaded.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/jaspic-api.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/tomcat-i18n-cs.jar:${j2ee.server.home}/lib/tomcat-i18n-de.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/tomcat-i18n-ko.jar:${j2ee.server.home}/lib/tomcat-i18n-pt-BR.jar:${j2ee.server.home}/lib/tomcat-i18n-ru.jar:${j2ee.server.home}/lib/tomcat-i18n-zh-CN.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/tomcat-jni.jar:${j2ee.server.home}/lib/tomcat-util-scan.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-websocket.jar:${j2ee.server.home}/lib/websocket-api.jar:${j2ee.server.home}/lib/websocket-client-api.jar +j2ee.platform.classpath=${j2ee.server.home}/bin/tomcat-juli.jar:${j2ee.server.home}/lib/annotations-api.jar:${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/catalina-ssi.jar:${j2ee.server.home}/lib/catalina-storeconfig.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/ecj-4.31.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/jakartaee-migration-1.0.8-shaded.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/jaspic-api.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/tomcat-i18n-cs.jar:${j2ee.server.home}/lib/tomcat-i18n-de.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/tomcat-i18n-ko.jar:${j2ee.server.home}/lib/tomcat-i18n-pt-BR.jar:${j2ee.server.home}/lib/tomcat-i18n-ru.jar:${j2ee.server.home}/lib/tomcat-i18n-zh-CN.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/tomcat-jni.jar:${j2ee.server.home}/lib/tomcat-util-scan.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-websocket.jar:${j2ee.server.home}/lib/websocket-api.jar:${j2ee.server.home}/lib/websocket-client-api.jar j2ee.server.type=Tomcat jar.compress=false javac.classpath=\ @@ -72,7 +91,25 @@ javac.classpath=\ ${file.reference.jackson-annotations-2.17.2.jar}:\ ${file.reference.jackson-core-2.17.2.jar}:\ ${file.reference.jackson-databind-2.17.2.jar}:\ - ${file.reference.gson-2.3.1.jar} + ${file.reference.cloudinary-core-1.33.0.jar}:\ + ${file.reference.cloudinary-http44-1.39.0.jar}:\ + ${file.reference.commons-codec-1.17.1.jar}:\ + ${file.reference.commons-io-2.17.0.jar}:\ + ${file.reference.commons-logging-1.2.jar-1}:\ + ${file.reference.dotenv-java-3.0.2.jar}:\ + ${file.reference.httpclient-4.5.14.jar}:\ + ${file.reference.httpcore-4.4.16.jar}:\ + ${file.reference.httpmime-4.5.14.jar}:\ + ${file.reference.commons-fileupload-1.5.jar}:\ + ${file.reference.commons-io-2.11.0.jar}:\ + ${file.reference.dropbox-core-sdk-5.4.4.jar}:\ + ${file.reference.jackson-annotations-2.15.2.jar}:\ + ${file.reference.jackson-core-2.15.2.jar}:\ + ${file.reference.jackson-databind-2.15.2.jar}:\ + ${file.reference.javax.servlet-api-4.0.1.jar}:\ + ${file.reference.javax.servlet.jsp-api-2.3.3.jar}:\ + ${file.reference.slf4j-api-2.0.7.jar}:\ + ${file.reference.slf4j-simple-2.0.7.jar} # Space-separated list of extra javac options javac.compilerargs= javac.debug=true @@ -118,3 +155,158 @@ war.ear.name=${war.name} war.name=FUNET.war web.docbase.dir=web webinf.dir=web/WEB-INF +======= +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=true +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.web.dir}/WEB-INF/classes +build.classes.excludes=**/*.java,**/*.form +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +build.web.dir=${build.dir}/web +build.web.excludes=${build.classes.excludes} +client.urlPart= +compile.jsps=false +conf.dir=${source.root}/conf +debug.classpath=${build.classes.dir}:${javac.classpath} +debug.test.classpath=\ + ${run.test.classpath} +display.browser=true +# Files to be excluded from distribution war +dist.archive.excludes= +dist.dir=dist +dist.ear.war=${dist.dir}/${war.ear.name} +dist.javadoc.dir=${dist.dir}/javadoc +dist.war=${dist.dir}/${war.name} +excludes= +file.reference.cloudinary-core-1.33.0.jar=web\\assets\\library\\Cloudinary\\cloudinary-core-1.33.0.jar +file.reference.cloudinary-http44-1.39.0.jar=web\\assets\\library\\Cloudinary\\cloudinary-http44-1.39.0.jar +file.reference.commons-codec-1.17.1.jar=web\\assets\\library\\Cloudinary\\commons-codec-1.17.1.jar +file.reference.commons-io-2.17.0.jar=web\\assets\\library\\Cloudinary\\commons-io-2.17.0.jar +file.reference.commons-logging-1.2.jar=web\\assets\\library\\Cloudinary\\commons-logging-1.2.jar +file.reference.commons-logging-1.2.jar-1=web\\assets\\library\\commons-logging-1.2.jar +file.reference.dotenv-java-3.0.2.jar=web\\assets\\library\\Cloudinary\\dotenv-java-3.0.2.jar +file.reference.fluent-hc-4.5.5.jar=web\\assets\\library\\fluent-hc-4.5.5.jar +file.reference.gson-2.10.1.jar=web\\assets\\library\\gson-2.10.1.jar +file.reference.gson-2.3.1.jar=web\\assets\\library\\gson-2.3.1.jar +file.reference.httpclient-4.5.14.jar=web\\assets\\library\\Cloudinary\\httpclient-4.5.14.jar +file.reference.httpclient-4.5.5.jar=web\\assets\\library\\httpclient-4.5.5.jar +file.reference.httpcore-4.4.16.jar=web\\assets\\library\\Cloudinary\\httpcore-4.4.16.jar +file.reference.httpcore-4.4.9.jar=web\\assets\\library\\httpcore-4.4.9.jar +file.reference.httpmime-4.5.14.jar=web\\assets\\library\\Cloudinary\\httpmime-4.5.14.jar +file.reference.jackson-annotations-2.17.2.jar=web\\assets\\library\\jackson-annotations-2.17.2.jar +file.reference.jackson-core-2.17.2.jar=web\\assets\\library\\jackson-core-2.17.2.jar +file.reference.jackson-databind-2.17.2.jar=web\\assets\\library\\jackson-databind-2.17.2.jar +file.reference.jakarta.activation-api-2.1.3.jar=web\\assets\\library\\jakarta.activation-api-2.1.3.jar +file.reference.jakarta.json-api-2.1.3.jar=web\\assets\\library\\jakarta.json-api-2.1.3.jar +file.reference.jakarta.mail-2.0.1.jar=web\\assets\\library\\jakarta.mail-2.0.1.jar +file.reference.jakarta.servlet.jsp.jstl-3.0.1.jar=web\\assets\\library\\jakarta_jstl\\jakarta.servlet.jsp.jstl-3.0.1.jar +file.reference.jakarta.servlet.jsp.jstl-api-3.0.0.jar=web\\assets\\library\\jakarta_jstl\\jakarta.servlet.jsp.jstl-api-3.0.0.jar +file.reference.jakarta.websocket-api-2.2.0.jar=web\\assets\\library\\jakarta.websocket-api-2.2.0.jar +file.reference.jakarta.websocket-client-api-2.2.0.jar=web\\assets\\library\\jakarta.websocket-client-api-2.2.0.jar +file.reference.javaee-api-7.0.jar=web\\assets\\library\\javaee-api-7.0.jar +file.reference.jaxb-api-2.1.jar=web\\assets\\library\\jakarta_jstl\\jaxb-api-2.1.jar +file.reference.json-20240303.jar=web\\assets\\library\\json-20240303.jar +file.reference.mssql-jdbc-12.6.1.jre11.jar=web\\assets\\library\\Microsoft_JDBC_12.6\\mssql-jdbc-12.6.1.jre11.jar +file.reference.sqljdbc42.jar=web\\assets\\library\\jakarta_jstl\\sqljdbc42.jar +includes=** +j2ee.compile.on.save=true +j2ee.copy.static.files.on.save=true +j2ee.deploy.on.save=true +j2ee.platform=10-web +j2ee.platform.classpath=${j2ee.server.home}/bin/tomcat-juli.jar:${j2ee.server.home}/lib/annotations-api.jar:${j2ee.server.home}/lib/catalina-ant.jar:${j2ee.server.home}/lib/catalina-ha.jar:${j2ee.server.home}/lib/catalina-ssi.jar:${j2ee.server.home}/lib/catalina-storeconfig.jar:${j2ee.server.home}/lib/catalina-tribes.jar:${j2ee.server.home}/lib/catalina.jar:${j2ee.server.home}/lib/ecj-4.27.jar:${j2ee.server.home}/lib/el-api.jar:${j2ee.server.home}/lib/jakartaee-migration-1.0.8-shaded.jar:${j2ee.server.home}/lib/jasper-el.jar:${j2ee.server.home}/lib/jasper.jar:${j2ee.server.home}/lib/jaspic-api.jar:${j2ee.server.home}/lib/jsp-api.jar:${j2ee.server.home}/lib/servlet-api.jar:${j2ee.server.home}/lib/tomcat-api.jar:${j2ee.server.home}/lib/tomcat-coyote-ffm.jar:${j2ee.server.home}/lib/tomcat-coyote.jar:${j2ee.server.home}/lib/tomcat-dbcp.jar:${j2ee.server.home}/lib/tomcat-i18n-cs.jar:${j2ee.server.home}/lib/tomcat-i18n-de.jar:${j2ee.server.home}/lib/tomcat-i18n-es.jar:${j2ee.server.home}/lib/tomcat-i18n-fr.jar:${j2ee.server.home}/lib/tomcat-i18n-ja.jar:${j2ee.server.home}/lib/tomcat-i18n-ko.jar:${j2ee.server.home}/lib/tomcat-i18n-pt-BR.jar:${j2ee.server.home}/lib/tomcat-i18n-ru.jar:${j2ee.server.home}/lib/tomcat-i18n-zh-CN.jar:${j2ee.server.home}/lib/tomcat-jdbc.jar:${j2ee.server.home}/lib/tomcat-jni.jar:${j2ee.server.home}/lib/tomcat-util-scan.jar:${j2ee.server.home}/lib/tomcat-util.jar:${j2ee.server.home}/lib/tomcat-websocket.jar:${j2ee.server.home}/lib/websocket-api.jar:${j2ee.server.home}/lib/websocket-client-api.jar +j2ee.server.type=Tomcat +jar.compress=false +javac.classpath=\ + ${file.reference.httpmime-4.5.14.jar}${file.reference.gson-2.3.1.jar}:\ + ${file.reference.cloudinary-core-1.33.0.jar}:\ + ${file.reference.cloudinary-http44-1.39.0.jar}:\ + ${file.reference.commons-codec-1.17.1.jar}:\ + ${file.reference.commons-io-2.17.0.jar}:\ + ${file.reference.commons-logging-1.2.jar}:\ + ${file.reference.dotenv-java-3.0.2.jar}:\ + ${file.reference.httpclient-4.5.14.jar}:\ + ${file.reference.httpcore-4.4.16.jar}:\ + ${file.reference.httpmime-4.5.14.jar}:\ + ${file.reference.commons-logging-1.2.jar-1}:\ + ${file.reference.fluent-hc-4.5.5.jar}:\ + ${file.reference.gson-2.10.1.jar}:\ + ${file.reference.gson-2.3.1.jar}:\ + ${file.reference.httpclient-4.5.5.jar}:\ + ${file.reference.httpcore-4.4.9.jar}:\ + ${file.reference.jackson-annotations-2.17.2.jar}:\ + ${file.reference.jackson-core-2.17.2.jar}:\ + ${file.reference.jackson-databind-2.17.2.jar}:\ + ${file.reference.jakarta.activation-api-2.1.3.jar}:\ + ${file.reference.jakarta.json-api-2.1.3.jar}:\ + ${file.reference.jakarta.mail-2.0.1.jar}:\ + ${file.reference.jakarta.websocket-api-2.2.0.jar}:\ + ${file.reference.jakarta.websocket-client-api-2.2.0.jar}:\ + ${file.reference.javaee-api-7.0.jar}:\ + ${file.reference.json-20240303.jar}:\ + ${file.reference.jakarta.servlet.jsp.jstl-3.0.1.jar}:\ + ${file.reference.jakarta.servlet.jsp.jstl-api-3.0.0.jar}:\ + ${file.reference.jaxb-api-2.1.jar}:\ + ${file.reference.sqljdbc42.jar}:\ + ${file.reference.mssql-jdbc-12.6.1.jre11.jar}:\ + ${file.reference.slf4j-simple-2.0.7.jar}:\ + ${file.reference.commons-fileupload-1.5.jar}:\ + ${file.reference.commons-io-2.11.0.jar}:\ + ${file.reference.dropbox-core-sdk-5.4.4.jar}:\ + ${file.reference.jackson-annotations-2.15.2.jar}:\ + ${file.reference.jackson-core-2.15.2.jar}:\ + ${file.reference.jackson-databind-2.15.2.jar}:\ + ${file.reference.javax.servlet-api-4.0.1.jar}:\ + ${file.reference.javax.servlet.jsp-api-2.3.3.jar}:\ + ${file.reference.slf4j-api-2.0.7.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.debug=true +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=17 +javac.target=17 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.preview=true +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +lib.dir=${web.docbase.dir}/WEB-INF/lib +no.dependencies=false +persistence.xml.dir=${conf.dir} +platform.active=default_platform +resource.dir=setup +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +# Space-separated list of JVM arguments used when running a class with a main method or a unit test +# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value): +runmain.jvmargs= +source.encoding=UTF-8 +source.root=src +src.dir=${source.root}/java +test.src.dir=test +war.content.additional= +war.ear.name=${war.name} +war.name=FUNET.war +web.docbase.dir=web +webinf.dir=web/WEB-INF +>>>>>>> origin/main diff --git a/nbproject/project.xml b/nbproject/project.xml index 893d2e3..18e5b1d 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -7,43 +7,46 @@ 1.6.5 - ${file.reference.jakarta.servlet.jsp.jstl-3.0.1.jar} + ${file.reference.httpmime-4.5.14.jar}${file.reference.gson-2.3.1.jar} + + + ${file.reference.cloudinary-core-1.33.0.jar} WEB-INF/lib - ${file.reference.jakarta.servlet.jsp.jstl-api-3.0.0.jar} + ${file.reference.cloudinary-http44-1.39.0.jar} WEB-INF/lib - ${file.reference.mssql-jdbc-12.6.1.jre11.jar} + ${file.reference.commons-codec-1.17.1.jar} WEB-INF/lib - ${file.reference.jakarta.activation-api-2.1.3.jar} + ${file.reference.commons-io-2.17.0.jar} WEB-INF/lib - ${file.reference.jakarta.mail-2.0.1.jar} + ${file.reference.commons-logging-1.2.jar} WEB-INF/lib - ${file.reference.json-20240303.jar} + ${file.reference.dotenv-java-3.0.2.jar} WEB-INF/lib - ${file.reference.jakarta.json-api-2.1.3.jar} + ${file.reference.httpclient-4.5.14.jar} WEB-INF/lib - ${file.reference.jakarta.websocket-api-2.2.0.jar} + ${file.reference.httpcore-4.4.16.jar} WEB-INF/lib - ${file.reference.jakarta.websocket-client-api-2.2.0.jar} + ${file.reference.httpmime-4.5.14.jar} WEB-INF/lib - ${file.reference.commons-logging-1.2.jar} + ${file.reference.commons-logging-1.2.jar-1} WEB-INF/lib @@ -54,6 +57,9 @@ ${file.reference.gson-2.10.1.jar} WEB-INF/lib + + ${file.reference.gson-2.3.1.jar} + ${file.reference.httpclient-4.5.5.jar} WEB-INF/lib @@ -62,24 +68,102 @@ ${file.reference.httpcore-4.4.9.jar} WEB-INF/lib + + ${file.reference.jackson-annotations-2.17.2.jar} + WEB-INF/lib + + + ${file.reference.jackson-core-2.17.2.jar} + WEB-INF/lib + + + ${file.reference.jackson-databind-2.17.2.jar} + WEB-INF/lib + + + ${file.reference.jakarta.activation-api-2.1.3.jar} + WEB-INF/lib + + + ${file.reference.jakarta.json-api-2.1.3.jar} + WEB-INF/lib + + + ${file.reference.jakarta.mail-2.0.1.jar} + WEB-INF/lib + + + ${file.reference.jakarta.websocket-api-2.2.0.jar} + WEB-INF/lib + + + ${file.reference.jakarta.websocket-client-api-2.2.0.jar} + WEB-INF/lib + ${file.reference.javaee-api-7.0.jar} WEB-INF/lib - ${file.reference.jackson-annotations-2.17.2.jar} + ${file.reference.json-20240303.jar} WEB-INF/lib - ${file.reference.jackson-core-2.17.2.jar} + ${file.reference.jakarta.servlet.jsp.jstl-3.0.1.jar} WEB-INF/lib - ${file.reference.jackson-databind-2.17.2.jar} + ${file.reference.jakarta.servlet.jsp.jstl-api-3.0.0.jar} WEB-INF/lib - ${file.reference.gson-2.3.1.jar} + ${file.reference.jaxb-api-2.1.jar} + + + ${file.reference.sqljdbc42.jar} + + + ${file.reference.mssql-jdbc-12.6.1.jre11.jar} + WEB-INF/lib + + + ${file.reference.slf4j-simple-2.0.7.jar} + WEB-INF/lib + + + ${file.reference.commons-fileupload-1.5.jar} + WEB-INF/lib + + + ${file.reference.commons-io-2.11.0.jar} + WEB-INF/lib + + + ${file.reference.dropbox-core-sdk-5.4.4.jar} + WEB-INF/lib + + + ${file.reference.jackson-annotations-2.15.2.jar} + WEB-INF/lib + + + ${file.reference.jackson-core-2.15.2.jar} + WEB-INF/lib + + + ${file.reference.jackson-databind-2.15.2.jar} + WEB-INF/lib + + + ${file.reference.javax.servlet-api-4.0.1.jar} + WEB-INF/lib + + + ${file.reference.javax.servlet.jsp-api-2.3.3.jar} + WEB-INF/lib + + + ${file.reference.slf4j-api-2.0.7.jar} WEB-INF/lib diff --git a/src/java/Security/SHA512WithSalt.java b/src/java/Security/SHA512WithSalt.java index f1edca7..defe824 100644 --- a/src/java/Security/SHA512WithSalt.java +++ b/src/java/Security/SHA512WithSalt.java @@ -1,58 +1,58 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template - */ -package Security; - -import java.nio.charset.StandardCharsets; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.Base64; - -/** - * - * @author ADMIN - */ -public class SHA512WithSalt { - - //Tạo salt ngẫu nhiên ( nân cao bảo mật để chống lại các cuộc tấn công từ rainbow table - bảng tra cứu mật khẩu ) - - public static byte[] createSalt(){ - SecureRandom random = new SecureRandom(); - byte[] salt = new byte[16]; // mặc định salt có 16 byte - random.nextBytes(salt); // điền giá trị salt - return salt; - } - - public static String hashPassWordWithSHA512(String password, byte[] salt){ - try{ - - MessageDigest md = MessageDigest.getInstance("SHA-512"); - md.update(salt);//thêm salt vào trc khi hash - - //hashing mật khẩu - byte[] hashBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));//xử lý theo phương thức UTF_8 - - // Kết hợp salt vào sau đó mã hóa thành base64 để lưu trữ - byte[] hashPassword = new byte[salt.length + hashBytes.length]; - System.arraycopy(salt, 0, hashPassword, 0, salt.length); - System.arraycopy(hashBytes, 0, hashPassword, salt.length, hashBytes.length); - - return Base64.getEncoder().encodeToString(hashPassword); - - } catch (NoSuchAlgorithmException exception){ - throw new RuntimeException(exception); - } - } - - public static void main(String[] args) { - //test case thử - String password = "123"; - - byte[] salt = createSalt(); - String hashedPassword = hashPassWordWithSHA512(password, salt); - - System.out.println("Mật khẩu sau khi hash là: " + hashedPassword); - } -} \ No newline at end of file +///* +// * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license +// * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template +// */ +//package Security; +// +//import java.nio.charset.StandardCharsets; +//import java.security.MessageDigest; +//import java.security.NoSuchAlgorithmException; +//import java.security.SecureRandom; +//import java.util.Base64; +// +///** +// * +// * @author ADMIN +// */ +//public class SHA512WithSalt { +// +// //Tạo salt ngẫu nhiên ( nân cao bảo mật để chống lại các cuộc tấn công từ rainbow table - bảng tra cứu mật khẩu ) +// +// public static byte[] createSalt(){ +// SecureRandom random = new SecureRandom(); +// byte[] salt = new byte[16]; // mặc định salt có 16 byte +// random.nextBytes(salt); // điền giá trị salt +// return salt; +// } +// +// public static String hashPassWordWithSHA512(String password, byte[] salt){ +// try{ +// +// MessageDigest md = MessageDigest.getInstance("SHA-512"); +// md.update(salt);//thêm salt vào trc khi hash +// +// //hashing mật khẩu +// byte[] hashBytes = md.digest(password.getBytes(StandardCharsets.UTF_8));//xử lý theo phương thức UTF_8 +// +// // Kết hợp salt vào sau đó mã hóa thành base64 để lưu trữ +// byte[] hashPassword = new byte[salt.length + hashBytes.length]; +// System.arraycopy(salt, 0, hashPassword, 0, salt.length); +// System.arraycopy(hashBytes, 0, hashPassword, salt.length, hashBytes.length); +// +// return Base64.getEncoder().encodeToString(hashPassword); +// +// } catch (NoSuchAlgorithmException exception){ +// throw new RuntimeException(exception); +// } +// } +// +// public static void main(String[] args) { +// //test case thử +// String password = "123"; +// +// byte[] salt = createSalt(); +// String hashedPassword = hashPassWordWithSHA512(password, salt); +// +// System.out.println("Mật khẩu sau khi hash là: " + hashedPassword); +// } +//} \ No newline at end of file diff --git a/src/java/com/vnpay/common/Config.java b/src/java/com/vnpay/common/Config.java index 45a32e1..b47bb8c 100644 --- a/src/java/com/vnpay/common/Config.java +++ b/src/java/com/vnpay/common/Config.java @@ -22,7 +22,7 @@ public class Config { public static String vnp_PayUrl = "https://sandbox.vnpayment.vn/paymentv2/vpcpay.html"; - public static String vnp_ReturnUrl = "http://localhost:8080/FUNET/vnpay_return.jsp"; + public static String vnp_ReturnUrl = "http://localhost:80/FUNET/vnpay_return.jsp"; public static String vnp_TmnCode = "QMJKBD3P"; public static String secretKey = "Z4JWL3JJYKLRWOGQR98UVE65P2RBLQAK"; public static String vnp_ApiUrl = "https://sandbox.vnpayment.vn/merchant_webapi/api/transaction"; diff --git a/src/java/com/vnpay/common/ajaxServlet.java b/src/java/com/vnpay/common/ajaxServlet.java index f53ad2f..7e29fa2 100644 --- a/src/java/com/vnpay/common/ajaxServlet.java +++ b/src/java/com/vnpay/common/ajaxServlet.java @@ -42,7 +42,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws S String vnp_TmnCode = Config.vnp_TmnCode; - Map vnp_Params = new HashMap<>(); + Map vnp_Params = new HashMap<>(); vnp_Params.put("vnp_Version", vnp_Version); vnp_Params.put("vnp_Command", vnp_Command); vnp_Params.put("vnp_TmnCode", vnp_TmnCode); diff --git a/src/java/controller/AddCartServlet.java b/src/java/controller/AddCartServlet.java index b93cc80..061887e 100644 --- a/src/java/controller/AddCartServlet.java +++ b/src/java/controller/AddCartServlet.java @@ -56,4 +56,4 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) } } -} +} \ No newline at end of file diff --git a/src/java/controller/AdminDeleteServlet.java b/src/java/controller/AdminDeleteServlet.java new file mode 100644 index 0000000..bf62d05 --- /dev/null +++ b/src/java/controller/AdminDeleteServlet.java @@ -0,0 +1,117 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.UserActivityDAO; +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Quocb + */ +public class AdminDeleteServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet AdminDeleteServlet"); + out.println(""); + out.println(""); + out.println("

Servlet AdminDeleteServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String type = request.getParameter("type"); + int id = Integer.parseInt(request.getParameter("idtype")); + int userId = Integer.parseInt(request.getParameter("userId")); + postDAO postDAO = new postDAO(); + UserActivityDAO useractivitydao=new UserActivityDAO(); + if (type.equals("Post")) { + Logger.getLogger(userpageServlet.class.getName()).info("try to delete post"); + + try { + useractivitydao.deleteUserActivityByPostId(id); + postDAO.deletePost(id); + Logger.getLogger(userpageServlet.class.getName()).info("delete post complete"); + } catch (Exception ex) { + Logger.getLogger(userpageServlet.class.getName()).log(Level.SEVERE, null, ex); + } + + response.sendRedirect("log?id="+userId); + } + if (type.equals("Comment")){ + Logger.getLogger(userpageServlet.class.getName()).info("try to delete comment"); + try { + useractivitydao.deleteUserActivityByCommentId(id); + postDAO.deleteComment(id); + Logger.getLogger(userpageServlet.class.getName()).info("delete comment complete"); + } catch (Exception ex) { + Logger.getLogger(userpageServlet.class.getName()).log(Level.SEVERE, null, ex); + } + response.sendRedirect("log?id="+userId); + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/BanServlet.java b/src/java/controller/BanServlet.java new file mode 100644 index 0000000..de44f54 --- /dev/null +++ b/src/java/controller/BanServlet.java @@ -0,0 +1,93 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.AdminDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * + * @author Quocb + */ +public class BanServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet BanServlet"); + out.println(""); + out.println(""); + out.println("

Servlet BanServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + Integer id=Integer.parseInt( request.getParameter("id")); + String action=request.getParameter("action"); + AdminDAO dao=new AdminDAO(); + if (action.equalsIgnoreCase("ban")){ + dao.updateUserBanStatus(id, true); + } + else dao.updateUserBanStatus(id, false); + request.getRequestDispatcher("log?id="+id).forward(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/ConversationRestController.java b/src/java/controller/ConversationRestController.java index c1c7aab..b424100 100644 --- a/src/java/controller/ConversationRestController.java +++ b/src/java/controller/ConversationRestController.java @@ -30,10 +30,7 @@ */ public class ConversationRestController extends HttpServlet { - private ConversationDAO conversationDAO = ConversationDAO.getInstance(); - private userDAO userDao = userDAO.getInstance(); - private ObjectMapper objectMapper = new ObjectMapper(); - private ConversationService conversationService = ConversationService.getInstance(); + private static final Logger LOGGER = Logger.getLogger(ConversationRestController.class.getName()); /** * Processes requests for both HTTP GET and POST @@ -77,12 +74,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) String usersConversationId = request.getParameter("usersConversationId"); String messagesConversationId = request.getParameter("messagesConversationId"); String conversationKeyword = request.getParameter("conversationKeyword"); - String json = "Must have username or conversation id as request param"; + String json = ""; + ConversationService conversationService = ConversationService.getInstance(); ObjectMapper objectMapper = new ObjectMapper(); try { if (conversationKeyword != null && !conversationKeyword.isEmpty() && user_id != null && !user_id.isEmpty()) { - + LOGGER.info("Fetching conversations by keyword for user"); List conversationDTOs = conversationService .getConversationsOfUserByKeyword(Integer.parseInt(user_id), conversationKeyword); for (ConversationDTO c : conversationDTOs) { @@ -92,21 +90,17 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } json = objectMapper.writeValueAsString(conversationDTOs); - } else if (user_id != null && !user_id.isEmpty()) { - + } else if (user_id != null) { List conversationDTOs = conversationService .getAllConversationsById(Integer.parseInt(user_id)); for (ConversationDTO conversationDTO : conversationDTOs) { - conversationDTO - .setUsers(conversationService.getAllUsersByConversationId(conversationDTO.getId())); + conversationDTO.setUsers(conversationService.getAllUsersByConversationId(conversationDTO.getId())); } json = objectMapper.writeValueAsString(conversationDTOs); - } else if (usersConversationId != null && !usersConversationId.isEmpty()) { - + LOGGER.info("Fetch go here"); int id = Integer.parseInt(usersConversationId); List userDTOs = conversationService.getAllUsersByConversationId(id); - json = objectMapper.writeValueAsString(userDTOs); } else if (messagesConversationId != null && !messagesConversationId.isEmpty()) { @@ -118,7 +112,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) } } catch (Exception e) { - + e.printStackTrace(); } response.setContentType("application/json"); @@ -139,17 +133,19 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ConversationService conversationService = ConversationService.getInstance(); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter printWriter = response.getWriter(); String json = ""; StringBuilder requestBody = new StringBuilder(); - String line; + String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { requestBody.append(line); + Logger.getLogger(ConversationRestController.class.getName()).info(line); } } catch (IOException ex) { json = "{\"error\":\"" + ex.getMessage() + "\"}"; @@ -157,15 +153,16 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) printWriter.flush(); return; } + LOGGER.info(requestBody.toString()); + ObjectMapper objectMapper = new ObjectMapper(); + ConversationDTO conversation = objectMapper.readValue(requestBody.toString(), ConversationDTO.class); try { - Conversation conversation = objectMapper.readValue(requestBody.toString(), Conversation.class); - conversationDAO.saveConversation(conversation, null); // Assuming this method works with pure objects - json = objectMapper.writeValueAsString(conversation); + conversationService.saveConversation(conversation); } catch (Exception ex) { - json = "{\"error\":\"" + ex.getMessage() + "\"}"; + Logger.getLogger(ConversationRestController.class.getName()).log(Level.SEVERE, null, ex); } - + json = objectMapper.writeValueAsString(conversation); printWriter.print(json); printWriter.flush(); } @@ -175,19 +172,19 @@ protected void doDelete(HttpServletRequest request, HttpServletResponse response throws ServletException, IOException { String user_id = request.getParameter("user_id"); String conversationId = request.getParameter("conversationId"); - String json = "Must have username or conversation id as request param"; + String json = "Must have userId or conversation id as request param"; if (conversationId != null && !conversationId.isEmpty()) { int id = Integer.parseInt(conversationId); if (user_id != null && !user_id.isEmpty()) { try { - conversationDAO.deleteUserFromConversation(id, Integer.parseInt(user_id)); + ConversationService.getInstance().deleteUserFromConversation(id, Integer.parseInt(user_id)); } catch (Exception ex) { Logger.getLogger(ConversationRestController.class.getName()).log(Level.SEVERE, null, ex); } json = "delete User by Id " + user_id + " From Conversation by Id " + id + " successfully"; } else { try { - conversationDAO.deleteConversationById(id); + ConversationService.getInstance().deleteConversationById(id); } catch (Exception ex) { Logger.getLogger(ConversationRestController.class.getName()).log(Level.SEVERE, null, ex); } @@ -213,4 +210,4 @@ public String getServletInfo() { return "Short description"; }// -} +} \ No newline at end of file diff --git a/src/java/controller/CreMaterialServlet.java b/src/java/controller/CreMaterialServlet.java new file mode 100644 index 0000000..8659f7f --- /dev/null +++ b/src/java/controller/CreMaterialServlet.java @@ -0,0 +1,184 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import com.dropbox.core.DbxRequestConfig; +import com.dropbox.core.v2.DbxClientV2; +import com.dropbox.core.v2.files.WriteMode; +import dao.learningMaterialDao; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.MultipartConfig; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.Part; +import java.io.InputStream; +import java.lang.System.Logger; +import java.lang.System.Logger.Level; +import java.util.Date; +import model.LearningMaterial; +import model.User; + +/** + * + * @author Quocb + */ +@MultipartConfig +public class CreMaterialServlet extends HttpServlet { + + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(CreMaterialServlet.class.getName()); + + private static final String ACCESS_TOKEN = "sl.B_oVGLZBc_ZXr3lMWjy6DxIkooVzryaLCDrIp-mFaw3mFLxWlIqpC_vM1GYdC9t8A8XaevphHfLB_kuu5wTp_suI_wNCVWdDdFL6ldE37u2tB8ilYGFjuOLAsJqqgNfAlD9ctkXBGLzD2yieqHJmkPo"; + private DbxClientV2 client; + + @Override + public void init() throws ServletException { + logger.info("Initializing Dropbox client..."); + DbxRequestConfig config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build(); + client = new DbxClientV2(config, ACCESS_TOKEN); + logger.info("Dropbox client initialized."); + } + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet CreMaterialServlet"); + out.println(""); + out.println(""); + out.println("

Servlet CreMaterialServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + private String getFileName(Part part) { + String contentDisp = part.getHeader("content-disposition"); + String[] tokens = contentDisp.split(";"); + + for (String token : tokens) { + if (token.trim().startsWith("filename")) { + return token.substring(token.indexOf("=") + 2, token.length() - 1); + } + } + return ""; + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + logger.info("User session found. Proceeding with file upload."); + User user = (User) session.getAttribute("user"); + int userId = user.getUser_id(); + + String name = request.getParameter("name"); + String description = request.getParameter("description"); + if(description==null){ + response.sendRedirect("ngu"); +return; + } + Part filePart = request.getPart("context"); + String context = getFileName(filePart); + String subjectCode = request.getParameter("subjectCode"); + String departmentIdStr = request.getParameter("departmentId"); + String review = request.getParameter("review"); + + try { + InputStream inputStream = filePart.getInputStream(); + logger.info("Uploading file to Dropbox: " + context); + client.files().uploadBuilder("/" + context) + .withMode(WriteMode.OVERWRITE) + .uploadAndFinish(inputStream); + logger.info("File uploaded successfully."); + + } catch (Exception e) { + logger.info("Error uploading file to Dropbox"); + response.sendRedirect("lmaterialLink"); +return; + } + + int departmentId; + try { + departmentId = Integer.parseInt(departmentIdStr); + logger.info("Parsed department ID: " + departmentId); + } catch (NumberFormatException e) { + response.sendRedirect("lmaterialLink"); + return; + } + + Date publishDate = new Date(); + + LearningMaterial learningMaterial = new LearningMaterial(0, userId, name, description, context, subjectCode, publishDate, review, departmentId); + + learningMaterialDao dao = new learningMaterialDao(); + try { + dao.createLearningMaterial(learningMaterial); + logger.info("Learning material created successfully."); + request.setAttribute("successMessage", "Learning Material created successfully"); + response.sendRedirect("lmaterialLink"); + } catch (Exception e) { + e.printStackTrace(); + request.setAttribute("errorMessage", "Error creating learning material"); + response.sendRedirect("lmaterialLink"); + } + } else { + response.sendRedirect("login.jsp"); // Redirect to login page if user is not logged in + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} \ No newline at end of file diff --git a/src/java/controller/DashBoardServlet.java b/src/java/controller/DashBoardServlet.java new file mode 100644 index 0000000..32380d4 --- /dev/null +++ b/src/java/controller/DashBoardServlet.java @@ -0,0 +1,79 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.MonthDAO; +import dao.postDAO; +import dao.userDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import model.Month; +import model.User; +import model.UserActivityLog; + +/** + * + * @author Quocb + */ +//@WebServlet("/dashBoard") +public class DashBoardServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + userDAO userdao = new userDAO(); + MonthDAO monthdao = new MonthDAO(); + List results = monthdao.Get7Month(); + request.setAttribute("label0", results.get(0).getName()); + request.setAttribute("label1", results.get(1).getName()); + request.setAttribute("label2", results.get(2).getName()); + request.setAttribute("label3", results.get(3).getName()); + request.setAttribute("label4", results.get(4).getName()); + request.setAttribute("label5", results.get(5).getName()); + request.setAttribute("label6", results.get(6).getName()); + request.setAttribute("data0", results.get(0).getCount() != null ? results.get(0).getCount() : 0); + request.setAttribute("data1", results.get(1).getCount() != null ? results.get(1).getCount() : 0); + request.setAttribute("data2", results.get(2).getCount() != null ? results.get(2).getCount() : 0); + request.setAttribute("data3", results.get(3).getCount() != null ? results.get(3).getCount() : 0); + request.setAttribute("data4", results.get(4).getCount() != null ? results.get(4).getCount() : 0); + request.setAttribute("data5", results.get(5).getCount() != null ? results.get(5).getCount() : 0); + request.setAttribute("data6", results.get(6).getCount() != null ? results.get(6).getCount() : 0); + + try { + // request.setAttribute("",); + //request.setAttribute("activities",activities); + ArrayList users = userdao.getAllUsers(); + request.setAttribute("users", users); + } catch (Exception ex) { + Logger.getLogger(DashBoardServlet.class.getName()).log(Level.SEVERE, null, ex); + } + request.getRequestDispatcher("/WEB-INF/DashBoard.jsp").forward(request, response); + } + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + } + + @Override + public String getServletInfo() { + return "Short description"; + }// + +} \ No newline at end of file diff --git a/src/java/controller/DeleteProductServlet.java b/src/java/controller/DeleteProductServlet.java index bea23cd..ad37e80 100644 --- a/src/java/controller/DeleteProductServlet.java +++ b/src/java/controller/DeleteProductServlet.java @@ -6,9 +6,13 @@ import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.util.List; +import model.Product; +import model.User; public class DeleteProductServlet extends HttpServlet { - protected void doPost(HttpServletRequest request, HttpServletResponse response) + + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int productId = Integer.parseInt(request.getParameter("product_id")); productDAO dao = new productDAO(); @@ -18,10 +22,32 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) response.sendRedirect(request.getContextPath() + "/SellingProductServlet"); } else { request.setAttribute("error", "Error deleting product."); + productDAO productDAO = new productDAO(); + + List productList = null; + try { + User currentUser = (User) request.getSession(false).getAttribute("user"); + productList = productDAO.getSellingList(currentUser.getUser_id()); + } catch (Exception ex) { + ex.printStackTrace(); + } + + request.setAttribute("productList", productList); request.getRequestDispatcher("WEB-INF/selling.jsp").forward(request, response); } } catch (Exception e) { - request.setAttribute("error", "An error occurred: " + e.getMessage()); + request.setAttribute("error", "You cannot delete product because the product is on transaction"); + productDAO productDAO = new productDAO(); + + List productList = null; + try { + User currentUser = (User) request.getSession(false).getAttribute("user"); + productList = productDAO.getSellingList(currentUser.getUser_id()); + } catch (Exception ex) { + ex.printStackTrace(); + } + + request.setAttribute("productList", productList); request.getRequestDispatcher("WEB-INF/selling.jsp").forward(request, response); } } diff --git a/src/java/controller/DownloadMaterialServlet.java b/src/java/controller/DownloadMaterialServlet.java new file mode 100644 index 0000000..a24f832 --- /dev/null +++ b/src/java/controller/DownloadMaterialServlet.java @@ -0,0 +1,113 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import com.dropbox.core.DbxRequestConfig; +import com.dropbox.core.v2.DbxClientV2; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.lang.System.Logger.Level; + +/** + * + * @author Quocb + */ +public class DownloadMaterialServlet extends HttpServlet { + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(DownloadMaterialServlet.class.getName()); + + private static final String ACCESS_TOKEN = "sl.B_oVGLZBc_ZXr3lMWjy6DxIkooVzryaLCDrIp-mFaw3mFLxWlIqpC_vM1GYdC9t8A8XaevphHfLB_kuu5wTp_suI_wNCVWdDdFL6ldE37u2tB8ilYGFjuOLAsJqqgNfAlD9ctkXBGLzD2yieqHJmkPo"; + private DbxClientV2 client; + + @Override + public void init() throws ServletException { + logger.info("Initializing Dropbox client..."); + DbxRequestConfig config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build(); + client = new DbxClientV2(config, ACCESS_TOKEN); + logger.info("Dropbox client initialized."); + } + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet DownloadMaterialServlet"); + out.println(""); + out.println(""); + out.println("

Servlet DownloadMaterialServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String fileName= request.getParameter("name"); + + try { + response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); + response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); + + client.files().downloadBuilder("/" + fileName) + .download(response.getOutputStream()); + + } catch (Exception e) { + logger.info( "Error downloading file " + fileName); + + } + + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} \ No newline at end of file diff --git a/src/java/controller/MessageServlet.java b/src/java/controller/FileUploadServlet.java similarity index 61% rename from src/java/controller/MessageServlet.java rename to src/java/controller/FileUploadServlet.java index 47dbdc7..48032f1 100644 --- a/src/java/controller/MessageServlet.java +++ b/src/java/controller/FileUploadServlet.java @@ -4,22 +4,29 @@ */ package controller; -import com.google.gson.Gson; -import dao.MessageDao; +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import model.Message; -import java.util.List; +import jakarta.servlet.http.Part; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.util.Map; +import java.util.logging.Logger; +import util.CloudinaryAPI; /** * * @author HELLO */ -public class MessageServlet extends HttpServlet { +@MultipartConfig +public class FileUploadServlet extends HttpServlet { /** * Processes requests for both HTTP GET and POST @@ -38,10 +45,10 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re out.println(""); out.println(""); out.println(""); - out.println("Servlet MessageServlet"); + out.println("Servlet FileUploadServlet"); out.println(""); out.println(""); - out.println("

Servlet MessageServlet at " + request.getContextPath() + "

"); + out.println("

Servlet FileUploadServlet at " + request.getContextPath() + "

"); out.println(""); out.println(""); } @@ -57,26 +64,9 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re * @throws IOException if an I/O error occurs */ @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - int userId = Integer.parseInt(request.getParameter("userId")); - - try { - List messages = MessageDao.getInstance().findAllMessagesBySenderAndReceiver((int) request.getSession().getAttribute("user_id"), userId); - - // Convert messages to JSON - String json = new Gson().toJson(messages); - - // Set response content type - response.setContentType("application/json"); - response.setCharacterEncoding("UTF-8"); - - // Send JSON response back - response.getWriter().write(json); - } catch (Exception e) { - e.printStackTrace(); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.getWriter().write("Failed to load messages."); - } + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); } /** @@ -90,20 +80,28 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - int sender = Integer.parseInt(request.getParameter("sender")); - int receiver = Integer.parseInt(request.getParameter("receiver")); - String messageText = request.getParameter("message"); - - Message message = new Message(sender, receiver, messageText); + Part filePart = request.getPart("file"); + File tempFile = File.createTempFile("upload_", filePart.getSubmittedFileName()); try { - MessageDao.getInstance().saveMessage(message); - // Optionally, you can return a success response to the client - response.getWriter().write("Message saved successfully"); + InputStream inputStream = filePart.getInputStream(); + FileOutputStream outputStream = new FileOutputStream(tempFile); + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + Logger.getLogger(FileUploadServlet.class.getName()).info(tempFile.toString()); + // Upload to Cloudinary + Map uploadResult = CloudinaryAPI.getInstance().uploader().upload(tempFile, ObjectUtils.emptyMap()); + String fileUrl = (String) uploadResult.get("url"); + + // Send the URL back to the client + response.setContentType("application/json"); + response.getWriter().write("{\"url\": \"" + fileUrl + "\"}"); } catch (Exception e) { - // Handle exceptions appropriately response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.getWriter().write("Failed to save message: " + e.getMessage()); + response.getWriter().write("Error uploading file: " + e.getMessage()); } } diff --git a/src/java/controller/GameServlet.java b/src/java/controller/GameServlet.java new file mode 100644 index 0000000..53f6ec4 --- /dev/null +++ b/src/java/controller/GameServlet.java @@ -0,0 +1,62 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + + +import dao.gameDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import model.game; + +/** + * + * @author Quocb + */ +@WebServlet("/game") +public class GameServlet extends HttpServlet { + + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String category = request.getParameter("category"); + List list = new ArrayList(); + gameDAO gamedao = new gameDAO(); + list = gamedao.getAllGames(); + request.setAttribute("list", list); + request.getRequestDispatcher("WEB-INF/game.jsp").forward(request, response); + + + + + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + } + + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/LogServlet.java b/src/java/controller/LogServlet.java new file mode 100644 index 0000000..88d2af4 --- /dev/null +++ b/src/java/controller/LogServlet.java @@ -0,0 +1,88 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * + * @author Quocb + */ +@WebServlet("/log") +public class LogServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet LogServlet"); + out.println(""); + out.println(""); + out.println("

Servlet LogServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String id=request.getParameter("id"); + request.getRequestDispatcher("/WEB-INF/log.jsp?id="+id).forward(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/SearchGameServlet.java b/src/java/controller/SearchGameServlet.java new file mode 100644 index 0000000..22fdb53 --- /dev/null +++ b/src/java/controller/SearchGameServlet.java @@ -0,0 +1,72 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + + +import dao.SearchGameDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.List; +import model.game; + +/** + * + * @author Quocb + */ +@WebServlet("/searchGame") +public class SearchGameServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String keyword = request.getParameter("keyword"); + SearchGameDAO searchdao = new SearchGameDAO(); + List list = searchdao.searchGameByKeyword(keyword); + + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = response.getWriter(); + + if (list.isEmpty()) { + out.println("
" + + "
" + + "
" + + "

Không tìm thấy kết quả

" + + "
" + + "
"); + } else { + for (game sanPham : list) { + // Tạo mỗi game thành một div có hình ảnh, tên và thể loại game + out.println(""); + } + } + out.close(); + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + } + + @Override + public String getServletInfo() { + return "Short description"; + }// + +} \ No newline at end of file diff --git a/src/java/controller/UpdateDiaryServlet.java b/src/java/controller/UpdateDiaryServlet.java new file mode 100644 index 0000000..bbf9aac --- /dev/null +++ b/src/java/controller/UpdateDiaryServlet.java @@ -0,0 +1,101 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.UserActivityDAO; +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.lang.System.Logger; +import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; +import java.util.List; +import model.UserActivityLog; + +/** + * + * @author Quocb + */ +@WebServlet("/updateDiary") +public class UpdateDiaryServlet extends HttpServlet { + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(UpdateDiaryServlet.class.getName()); + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + UserActivityDAO dao = new UserActivityDAO(); + Integer userId = Integer.valueOf(request.getParameter("userId")); + + + List activities = dao.getUserActivities(userId); + + response.setContentType("text/html"); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + for (UserActivityLog activity : activities) { + String typeValue; + if (activity.getCommentId() == 0) { + + + typeValue = "Post"; + } else { + + typeValue = "Comment"; + + } + + int idTypeValue; + if (activity.getCommentId() != 0) { + idTypeValue = activity.getCommentId(); + } else { + idTypeValue = activity.getPostId(); + } + + out.println(""); + out.println("" + activity.getUserId() + ""); + out.println("" + activity.getRole() + ""); + out.println("" + activity.getFirstName() + " " + activity.getLastName() + ""); + out.println("" + activity.getActivityType() + ""); + out.println("" + activity.getPostId() + ""); + out.println("" + activity.getCommentId() + ""); + out.println("" + activity.getActivityDetails() + ""); + out.println(" " + activity.getTimestamp().format(formatter) + ""); + out.print(""); + out.println("
"); + out.println(""); + out.print(""); + out.println(""); + out.println(""); + out.println("
"); + out.print(""); + out.println(""); + + // Log activity details for debugging + + } + + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + } + + @Override + public String getServletInfo() { + return "Short description"; + }// + +} \ No newline at end of file diff --git a/src/java/controller/UserChartData.java b/src/java/controller/UserChartData.java new file mode 100644 index 0000000..b30dfae --- /dev/null +++ b/src/java/controller/UserChartData.java @@ -0,0 +1,59 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.MonthDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import model.Month; +import org.json.JSONObject; + +/** + * + * @author Quocb + */ +@WebServlet("/userChartData") +public class UserChartData extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + + JSONObject jsonResponse = new JSONObject(); + + MonthDAO dao=new MonthDAO(); + Month mon=dao.getLastMonthRegistrationCountAndName(); + String month = mon.getName(); + int userCount = mon.getCount(); + + jsonResponse.put("month", month); + jsonResponse.put("userCount", userCount); + + PrintWriter out = response.getWriter(); + out.print(jsonResponse.toString()); + out.flush(); + } + + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + + } + + + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/UserRestController.java b/src/java/controller/UserRestController.java index b359f6a..3cea4ac 100644 --- a/src/java/controller/UserRestController.java +++ b/src/java/controller/UserRestController.java @@ -70,16 +70,23 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) List listUsers = null; if (conversationId != null && !conversationId.isEmpty()) { int id = Integer.parseInt(conversationId); - //listUsers = userService.getFriendsNotInConversation(user_id, keyWord, id); + try { + listUsers = userDAO.getInstance().getFriendsNotInConversation(Integer.parseInt(user_id), keyWord, id); + Logger.getLogger(UserRestController.class.getName()).info("will it be here1"); + } catch (Exception ex) { + Logger.getLogger(UserRestController.class.getName()).log(Level.SEVERE, null, ex); + } } else if (keyWord.isEmpty()) { try { listUsers = userDAO.getInstance().getUserFriends(Integer.parseInt(user_id)); + Logger.getLogger(UserRestController.class.getName()).info("will it be here2"); } catch (Exception ex) { Logger.getLogger(UserRestController.class.getName()).log(Level.SEVERE, null, ex); } } else { try { listUsers = userDAO.getInstance().findFriendsByKeyWord(Integer.parseInt(user_id), keyWord); + Logger.getLogger(UserRestController.class.getName()).info("will it be here3"); } catch (Exception ex) { Logger.getLogger(UserRestController.class.getName()).log(Level.SEVERE, null, ex); } @@ -90,7 +97,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); - + PrintWriter printWriter = response.getWriter(); printWriter.print(json); printWriter.flush(); @@ -120,4 +127,4 @@ public String getServletInfo() { return "Short description"; }// -} +} \ No newline at end of file diff --git a/src/java/controller/VerifyServlet.java b/src/java/controller/VerifyServlet.java index 3d35231..5be8854 100644 --- a/src/java/controller/VerifyServlet.java +++ b/src/java/controller/VerifyServlet.java @@ -74,6 +74,50 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ +// @Override +// protected void doPost(HttpServletRequest request, HttpServletResponse response) +// throws ServletException, IOException { +// String act = request.getParameter("action"); +// HttpSession session = request.getSession(false); +// String otp = (String) session.getAttribute("otpCode"); +// String email = (String) session.getAttribute("pendingEmail"); +// +// if ("resend".equals(act)) { +// SmtpProtocol smtpProtocol = new SmtpProtocol(); +// otp = Integer.toString(smtpProtocol.sendMail(email)); +// session.setAttribute("otpCode", otp); +// request.getRequestDispatcher("WEB-INF/verify.jsp").forward(request, response); +// } else { +// String inputOtp = (String) request.getParameter("otp-code"); +// if (otp.equals(inputOtp)) { +// if (act.equals("newPass")) { +// request.getRequestDispatcher("WEB-INF/newPassword.jsp").forward(request, response); +// } else { +// Map pendingUserInfo = (Map) session.getAttribute("pendingUserInfo"); +// User user = new User(); +// user.setEmail(email); +// user.setFirst_name(pendingUserInfo.get("firstName")); +// user.setLast_name(pendingUserInfo.get("lastName")); +// user.setPassword(pendingUserInfo.get("password")); +// user.setProfile_pic("default_avt.jpg"); +// user.setRole("student"); +// user.setStatus(false); +// try { +// userDao.hashPw(user.getFirst_name(), user.getLast_name(), user.getEmail(), user.getPassword(), user.getProfile_pic(), user.getRole()); +// } catch (Exception ex) { +// Logger.getLogger(VerifyServlet.class.getName()).log(Level.SEVERE, null, ex); +// } +// // Clean up session +// session.invalidate(); +// request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response); +// } +// } else { +// request.setAttribute("msg", "Invalid OTP. Please try again."); +// request.getRequestDispatcher("WEB-INF/verify.jsp").forward(request, response); +// } +// } +// } + @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -103,7 +147,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) user.setRole("student"); user.setStatus(false); try { - userDao.hashPw(user.getFirst_name(), user.getLast_name(), user.getEmail(), user.getPassword(), user.getProfile_pic(), user.getRole()); + userDao.register(user); } catch (Exception ex) { Logger.getLogger(VerifyServlet.class.getName()).log(Level.SEVERE, null, ex); } diff --git a/src/java/controller/changeAvatarServlet.java b/src/java/controller/changeAvatarServlet.java index 69597be..33568f0 100644 --- a/src/java/controller/changeAvatarServlet.java +++ b/src/java/controller/changeAvatarServlet.java @@ -89,7 +89,6 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Part file = request.getPart("profile_pic"); String profile_pic = file.getSubmittedFileName(); String uploadPath = getServletContext().getRealPath("/assets/profile_avt/") + profile_pic; -// String uploadPath = "D:/fpt/prj301/project/FUNET_FINAL/FUNET/Downloads/FUNET/web/assets/profile_avt/" + profile_pic; try { FileOutputStream fos = new FileOutputStream(uploadPath); InputStream is = file.getInputStream(); @@ -112,7 +111,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) request.setAttribute("errorMessage", "Error"); } } - response.sendRedirect("userpageServlet"); + response.sendRedirect("profile"); } /** diff --git a/src/java/controller/commentServlet.java b/src/java/controller/commentServlet.java index 126dfad..e22c195 100644 --- a/src/java/controller/commentServlet.java +++ b/src/java/controller/commentServlet.java @@ -4,16 +4,20 @@ */ package controller; +import com.google.gson.Gson; import dao.postDAO; import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.MultipartConfig; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import java.sql.SQLException; +import java.util.HashMap; import java.util.List; +import java.util.Map; import model.Comment; import model.Post; import model.User; @@ -22,6 +26,7 @@ * * @author bim26 */ +@MultipartConfig public class commentServlet extends HttpServlet { /** @@ -91,11 +96,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - HttpSession session = request.getSession(false); + HttpSession session = request.getSession(false); if (session != null && session.getAttribute("user") != null) { int post_id = Integer.parseInt(request.getParameter("post_id")); String commentContent = request.getParameter("commentContent"); - String sourceUrl = request.getParameter("sourceUrl"); postDAO postDAO = new postDAO(); User user = (User) session.getAttribute("user"); Comment comment = new Comment(); @@ -103,18 +107,30 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) comment.setPost_id(post_id); comment.setUser_id(user.getUser_id()); comment.setComment_text(commentContent); + comment.setFirst_name(user.getFirst_name()); + comment.setLast_name(user.getLast_name()); + comment.setProfile_pic(user.getProfile_pic()); } try { postDAO.addComment(comment); - - if (sourceUrl != null && sourceUrl.contains("profile")) { - response.sendRedirect("profile"); - } else { - response.sendRedirect("home"); - } + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + Map jsonResponse = new HashMap<>(); + jsonResponse.put("success", true); + jsonResponse.put("comment", comment); + out.print(new Gson().toJson(jsonResponse)); + out.flush(); } catch (Exception e) { e.printStackTrace(); - response.sendRedirect("error.jsp"); + response.setContentType("application/json"); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + Map jsonResponse = new HashMap<>(); + jsonResponse.put("success", false); + jsonResponse.put("error", e.getMessage()); + out.print(new Gson().toJson(jsonResponse)); + out.flush(); } } else { response.sendRedirect("login"); diff --git a/src/java/controller/deleteCommentServlet.java b/src/java/controller/deleteCommentServlet.java new file mode 100644 index 0000000..45799ac --- /dev/null +++ b/src/java/controller/deleteCommentServlet.java @@ -0,0 +1,106 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.UserActivityDAO; +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import model.Comment; +import model.Post; +import model.User; + +/** + * + * @author OS + */ +public class deleteCommentServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet deleteCommentServlet"); + out.println(""); + out.println(""); + out.println("

Servlet deleteCommentServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("application/json"); + HttpSession session = request.getSession(false); + int comment_id = Integer.parseInt(request.getParameter("commentId")); + UserActivityDAO useractivitydao=new UserActivityDAO(); + postDAO postDAO = new postDAO(); + try { + useractivitydao.deleteUserActivityByCommentId(comment_id); + postDAO.deleteComment(comment_id); + response.getWriter().write("{\"success\": true}"); + } catch (Exception ex) { + Logger.getLogger(userpageServlet.class.getName()).log(Level.SEVERE, null, ex); + response.getWriter().write("{\"success\": false}"); + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/deleteLearningMaterial.java b/src/java/controller/deleteLearningMaterial.java new file mode 100644 index 0000000..8bef186 --- /dev/null +++ b/src/java/controller/deleteLearningMaterial.java @@ -0,0 +1,118 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ + +package controller; + +import dao.learningMaterialDao; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import model.LearningMaterial; +import model.User; + +/** + * + * @author gabri + */ +public class deleteLearningMaterial extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST methods. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet deleteLearningMaterial"); + out.println(""); + out.println(""); + out.println("

Servlet deleteLearningMaterial at " + request.getContextPath () + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override +protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + String idStr = request.getParameter("id"); + User user = (User) session.getAttribute("user"); + + if (idStr == null) { + response.sendRedirect("lmaterialLink"); + return; + } + + int id; + try { + id = Integer.parseInt(idStr); + } catch (NumberFormatException e) { + response.sendRedirect("lmaterialLink"); + return; + } + + learningMaterialDao learningMaterialDao = new learningMaterialDao(); + try { + LearningMaterial lm = learningMaterialDao.getLearningMaterialById(id); + if (lm != null && lm.getUserId() == user.getUser_id()) { + learningMaterialDao.deleteLearningMaterial(id); + request.setAttribute("successMessage", "Learning Material deleted successfully"); + } else { + request.setAttribute("errorMessage", "You do not have permission to delete this learning material"); + } + response.sendRedirect("lmaterialLink"); + } catch (Exception e) { + e.printStackTrace(); + request.setAttribute("errorMessage", "Error deleting learning material"); + response.sendRedirect("lmaterialLink"); + } + } else { + response.sendRedirect("WEB-INF/login.jsp"); + } +} + /** + * Returns a short description of the servlet. + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/deleteServlet.java b/src/java/controller/deleteServlet.java index b1322f7..c7d89e4 100644 --- a/src/java/controller/deleteServlet.java +++ b/src/java/controller/deleteServlet.java @@ -4,6 +4,7 @@ */ package controller; +import dao.UserActivityDAO; import dao.postDAO; import java.io.IOException; import java.io.PrintWriter; @@ -85,7 +86,9 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) int postId = Integer.parseInt(request.getParameter("postId")); postDAO postDAO = new postDAO(); + UserActivityDAO useractivitydao=new UserActivityDAO(); try { + useractivitydao.deleteUserActivityByPostId(postId); postDAO.deletePost(postId); } catch (Exception ex) { Logger.getLogger(userpageServlet.class.getName()).log(Level.SEVERE, null, ex); diff --git a/src/java/controller/learningMaterialDepartmentSearch.java b/src/java/controller/learningMaterialDepartmentSearch.java new file mode 100644 index 0000000..64dacf5 --- /dev/null +++ b/src/java/controller/learningMaterialDepartmentSearch.java @@ -0,0 +1,97 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ + +package controller; + +import dao.learningMaterialDao; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.List; +import model.LearningMaterial; + +/** + * + * @author gabri + */ +public class learningMaterialDepartmentSearch extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST methods. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet learningMaterialDepartmentSearch"); + out.println(""); + out.println(""); + out.println("

Servlet learningMaterialDepartmentSearch at " + request.getContextPath () + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String departmentIdStr = request.getParameter("departmentId"); + learningMaterialDao dao = new learningMaterialDao(); + List learningMaterialsList; + try { + if (departmentIdStr == null || departmentIdStr.trim().isEmpty()) { + learningMaterialsList = dao.getAll(); + } else { + int departmentId = Integer.parseInt(departmentIdStr); + learningMaterialsList = dao.getByDepartment(departmentId); + } + request.setAttribute("learningMaterialsList", learningMaterialsList); + request.getRequestDispatcher("WEB-INF/LearningMaterial.jsp").forward(request, response); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/lmaterialLink.java b/src/java/controller/lmaterialLink.java index 9ee05bb..38e34ac 100644 --- a/src/java/controller/lmaterialLink.java +++ b/src/java/controller/lmaterialLink.java @@ -1,7 +1,13 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ + package controller; import dao.learningMaterialDao; import java.io.IOException; +import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; @@ -9,8 +15,44 @@ import java.util.List; import model.LearningMaterial; +/** + * + * @author gabri + */ public class lmaterialLink extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST methods. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet lmaterialLink"); + out.println(""); + out.println(""); + out.println("

Servlet lmaterialLink at " + request.getContextPath () + "

"); + out.println(""); + out.println(""); + } + } + // + /** + * Handles the HTTP GET method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -28,4 +70,27 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) request.getRequestDispatcher("WEB-INF/LearningMaterial.jsp").forward(request, response); // chuyển hướng đến lmaterial.jsp } -} \ No newline at end of file + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/notificationServlet.java b/src/java/controller/notificationServlet.java index f0da3d1..23783df 100644 --- a/src/java/controller/notificationServlet.java +++ b/src/java/controller/notificationServlet.java @@ -34,11 +34,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) request.setAttribute("ordersList", buyerOrders); request.setAttribute("sellerOrders", sellerOrders); - request.setAttribute("currentUserId", userId); + request.setAttribute("userId", userId); request.getRequestDispatcher("WEB-INF/marketNotification.jsp").forward(request, response); } catch (Exception ex) { Logger.getLogger(notificationServlet.class.getName()).log(Level.SEVERE, null, ex); } } -} +} \ No newline at end of file diff --git a/src/java/controller/postServlet.java b/src/java/controller/postServlet.java index 861fd92..8a3a7c6 100644 --- a/src/java/controller/postServlet.java +++ b/src/java/controller/postServlet.java @@ -1,9 +1,7 @@ -/* - * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license - * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template - */ package controller; +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; import dao.FriendDAO; import dao.postDAO; import model.Post; @@ -17,154 +15,162 @@ import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import jakarta.servlet.http.Part; +import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintWriter; +import java.nio.file.Files; import java.sql.SQLException; -import java.util.List; +import java.util.*; +import java.util.logging.Level; +import java.util.logging.Logger; +import util.CloudinaryAPI; -/** - * - * @author bim26 - */ -@MultipartConfig +@MultipartConfig( + fileSizeThreshold = 1024 * 1024 * 10, // 10 MB + maxFileSize = 1024 * 1024 * 50, // 50 MB + maxRequestSize = 1024 * 1024 * 100 // 100 MB +) public class postServlet extends HttpServlet { - private static final long serialVersionUID = 1L; + private static final Logger LOGGER = Logger.getLogger(postServlet.class.getName()); - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ - protected void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - response.setContentType("text/html;charset=UTF-8"); - try (PrintWriter out = response.getWriter()) { - /* TODO output your page here. You may use following sample code. */ - out.println(""); - out.println(""); - out.println(""); - out.println("Servlet postServlet"); - out.println(""); - out.println(""); - out.println("

Servlet postServlet at " + request.getContextPath() + "

"); - out.println(""); - out.println(""); - } - } + private static final Set ALLOWED_IMAGE_TYPES = new HashSet<>(Arrays.asList( + "image/jpeg", "image/png", "image/gif", "image/bmp", "image/webp" + )); + + private static final Set ALLOWED_VIDEO_TYPES = new HashSet<>(Arrays.asList( + "video/mp4", "video/mpeg", "video/quicktime", "video/x-msvideo", "video/webm" + )); + + private static final long serialVersionUID = 1L; - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + LOGGER.info("Processing GET request"); HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { User currentUser = (User) session.getAttribute("user"); - List posts = postDAO.getAllPosts(currentUser.getUser_id()); - postDAO dao = new postDAO(); - for (Post post : posts) { - try { + LOGGER.info("User " + currentUser.getUser_id() + " requesting posts"); + + try { + List posts = postDAO.getAllPosts(currentUser.getUser_id()); + postDAO dao = new postDAO(); + + for (Post post : posts) { post.setLikedByCurrentUser(dao.hasUserLikedPost(currentUser.getUser_id(), post.getPost_id())); - } catch (SQLException e) { - e.printStackTrace(); } - } - request.setAttribute("posts", posts); - try { + request.setAttribute("posts", posts); + LOGGER.info("Successfully retrieved " + posts.size() + " posts for user " + currentUser.getUser_id()); + FriendDAO friendDAO = new FriendDAO(); List friends = friendDAO.findFriend(currentUser.getUser_id()); request.setAttribute("friends", friends); + LOGGER.info("Successfully retrieved friends list for user " + currentUser.getUser_id()); + + } catch (SQLException e) { + LOGGER.log(Level.SEVERE, "Database error while processing GET request", e); } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error while retrieving friends", e); } + request.getRequestDispatcher("WEB-INF/home.jsp").forward(request, response); } else { + LOGGER.warning("Unauthorized access attempt - redirecting to login"); response.sendRedirect("login"); } } - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurse - * @throws IOException if an I/O error occurs - */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + LOGGER.info("Processing POST request"); HttpSession session = request.getSession(false); - // ------------------------------------------------------------------------------------------------- if (session != null && session.getAttribute("user") != null) { User user = (User) session.getAttribute("user"); + LOGGER.info("User " + user.getUser_id() + " attempting to create post"); + String body = request.getParameter("postContent"); - Part file = request.getPart("image"); + Part filePart = request.getPart("image"); String sourceUrl = request.getParameter("sourceUrl"); - String image_path = file.getSubmittedFileName(); -// String uploadPath = "D:/fpt/prj301/project/FUNET_FINAL/FUNET/Downloads/FUNET/web/assets/post_image/" + image_path; - String uploadPath = getServletContext().getRealPath("/assets/post_image/") + image_path; - //E:\FUNET\FUNET\web\assets - try { + String imageUrl = null; + String resourceType = null; - FileOutputStream fos = new FileOutputStream(uploadPath); - InputStream is = file.getInputStream(); + if (filePart != null && filePart.getSize() > 0) { + String contentType = filePart.getContentType(); + LOGGER.info("File upload detected with content type: " + contentType); - byte[] data = new byte[is.available()]; - is.read(data); - fos.write(data); - fos.close(); - } catch (Exception e) { - e.printStackTrace(); + if (!ALLOWED_IMAGE_TYPES.contains(contentType) && !ALLOWED_VIDEO_TYPES.contains(contentType)) { + LOGGER.warning("Unsupported file type attempted: " + contentType); + request.setAttribute("error", "Unsupported file type"); + response.sendRedirect(sourceUrl != null && sourceUrl.contains("profile") ? "profile" : "home"); + return; + } + + resourceType = ALLOWED_IMAGE_TYPES.contains(contentType) ? "image" : "video"; + + try { + File tempFile = File.createTempFile("upload_", filePart.getSubmittedFileName()); + LOGGER.info("Created temporary file for upload: " + tempFile.getName()); + + try (InputStream inputStream = filePart.getInputStream(); FileOutputStream outputStream = new FileOutputStream(tempFile)) { + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } + + Map uploadResult = CloudinaryAPI.getInstance().uploader().upload(tempFile, ObjectUtils.asMap( + "resource_type", resourceType + )); + imageUrl = (String) uploadResult.get("url"); + LOGGER.info("Successfully uploaded file to Cloudinary: " + imageUrl); + + Files.deleteIfExists(tempFile.toPath()); + LOGGER.info("Deleted temporary file: " + tempFile.getName()); + + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Error during file upload", e); + request.setAttribute("errorMessage", "Error uploading image"); + response.sendRedirect("home"); + return; + } } - if (!body.trim().equals("") || !image_path.equals("")) { + if (!body.trim().equals("") || imageUrl != null) { Post post = new Post(); post.setUser_id(user.getUser_id()); post.setBody(body); - post.setImage_path(image_path); - postDAO PostDao = new postDAO(); + post.setImage_path(imageUrl); + post.setType(resourceType); + try { + postDAO PostDao = new postDAO(); PostDao.addPost(post); + LOGGER.info("Successfully created new post for user " + user.getUser_id()); TimeUnit.SECONDS.sleep(2); - if (sourceUrl != null && sourceUrl.contains("profile")) { - response.sendRedirect("profile"); - } else { - response.sendRedirect("home"); - } + response.sendRedirect(sourceUrl != null && sourceUrl.contains("profile") ? "profile" : "home"); + } catch (Exception e) { - e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error saving post to database", e); request.setAttribute("errorMessage", "Error saving post"); response.sendRedirect("home"); } } else { + LOGGER.info("Empty post attempted - redirecting"); response.sendRedirect("home"); } } else { + LOGGER.warning("Unauthorized post attempt - redirecting to home"); response.sendRedirect("home"); } } - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ @Override public String getServletInfo() { - return "Short description"; + return "Post management servlet handling creation and retrieval of posts"; } } diff --git a/src/java/controller/saveLearningMaterial.java b/src/java/controller/saveLearningMaterial.java new file mode 100644 index 0000000..306b03b --- /dev/null +++ b/src/java/controller/saveLearningMaterial.java @@ -0,0 +1,101 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import com.google.gson.Gson; +import dao.learningMaterialDao; +import model.User; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.List; +import model.LearningMaterial; + +/** + * + * @author gabri + */ +public class saveLearningMaterial extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet saveLearningMaterial"); + out.println(""); + out.println(""); + out.println("

Servlet saveLearningMaterial at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override +protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + User currentUser = (User) request.getSession().getAttribute("user"); + learningMaterialDao dao = new learningMaterialDao(); + + try { + List savedMaterials = dao.getSavedLearningMaterials(currentUser.getUser_id()); + request.setAttribute("savedMaterialsList", savedMaterials); + request.getRequestDispatcher("savedLearningMaterials.jsp").forward(request, response); + } catch (Exception e) { + e.printStackTrace(); + response.sendRedirect("error.jsp"); + } +} + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + int learningMaterialId = Integer.parseInt(request.getParameter("id")); + User currentUser = (User) request.getSession().getAttribute("user"); + learningMaterialDao dao = new learningMaterialDao(); + + try { + dao.saveLearningMaterial(currentUser.getUser_id(), learningMaterialId); + response.sendRedirect("lmaterialLink"); + } catch (Exception e) { + e.printStackTrace(); + response.sendRedirect("error.jsp"); + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/savePostServlet.java b/src/java/controller/savePostServlet.java new file mode 100644 index 0000000..f6354cc --- /dev/null +++ b/src/java/controller/savePostServlet.java @@ -0,0 +1,119 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ + +package controller; + +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import model.User; +import java.sql.SQLException; +import java.util.List; +import model.Post; + +/** + * + * @author OS + */ +public class savePostServlet extends HttpServlet { + private static final long serialVersionUID = 1L; + + /** + * Processes requests for both HTTP GET and POST methods. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet savePostServlet"); + out.println(""); + out.println(""); + out.println("

Servlet savePostServlet at " + request.getContextPath () + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + User user = (User) session.getAttribute("user"); + int userId = user.getUser_id(); + postDAO dao = new postDAO(); + List savedPosts = dao.getSavedPosts(userId); + request.setAttribute("posts", savedPosts); + request.getRequestDispatcher("WEB-INF/savedPosts.jsp").forward(request, response); + } else { + response.sendRedirect("login"); + } + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + User user = (User) session.getAttribute("user"); + int userId = user.getUser_id(); + int postId = Integer.parseInt(request.getParameter("postId")); + postDAO dao = new postDAO(); + + try { + if (dao.isPostSavedByUser(userId, postId)) { + dao.unsavePost(userId, postId); + } else { + dao.savePost(userId, postId); + } + response.sendRedirect("home"); + } catch (SQLException e) { + e.printStackTrace(); + response.sendRedirect("home"); + } + } else { + response.sendRedirect("login"); + } + } + + + /** + * Returns a short description of the servlet. + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/searchLearningMaterial.java b/src/java/controller/searchLearningMaterial.java new file mode 100644 index 0000000..fcfd49a --- /dev/null +++ b/src/java/controller/searchLearningMaterial.java @@ -0,0 +1,96 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ + +package controller; + +import dao.learningMaterialDao; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.util.List; +import model.LearningMaterial; + +/** + * + * @author gabri + */ +public class searchLearningMaterial extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST methods. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet searchLearningMaterial"); + out.println(""); + out.println(""); + out.println("

Servlet searchLearningMaterial at " + request.getContextPath () + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String keyword = request.getParameter("search-name"); + learningMaterialDao dao = new learningMaterialDao(); + List learningMaterialsList; + try { + if (keyword == null || keyword.trim().isEmpty()) { + learningMaterialsList = dao.getAll(); + } else { + learningMaterialsList = dao.searchLearningMaterials(keyword); + } + request.setAttribute("learningMaterialsList", learningMaterialsList); + request.getRequestDispatcher("WEB-INF/LearningMaterial.jsp").forward(request, response); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Returns a short description of the servlet. + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/searchServlet.java b/src/java/controller/searchServlet.java index c8c3c14..4ca4dd4 100644 --- a/src/java/controller/searchServlet.java +++ b/src/java/controller/searchServlet.java @@ -69,7 +69,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) int currUser = (int) session.getAttribute("user_id"); String name = request.getParameter("search-name"); try { - ArrayList userList = userDAO.getAllUserByName(name, currUser); + ArrayList userList = userDAO.getInstance().findFriendsByKeyWord(currUser, name); FriendDAO friendDAO = new FriendDAO(); HashMap usersWithStatus = new HashMap<>(); diff --git a/src/java/controller/settingServlet.java b/src/java/controller/settingServlet.java index d075bba..f767cea 100644 --- a/src/java/controller/settingServlet.java +++ b/src/java/controller/settingServlet.java @@ -37,7 +37,7 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) sessionUser.setLast_name(lastName); userDao.updateUser(sessionUser); request.setAttribute("notification", "Your name has been changed to: " + firstName + " " + lastName); - response.sendRedirect("userpageServlet"); + response.sendRedirect("profile"); } case "changePassword" -> { String oldPassword = request.getParameter("oldPassword"); diff --git a/src/java/controller/updateCommentServlet.java b/src/java/controller/updateCommentServlet.java new file mode 100644 index 0000000..89f80dd --- /dev/null +++ b/src/java/controller/updateCommentServlet.java @@ -0,0 +1,107 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ + +package controller; + +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import java.util.concurrent.TimeUnit; +import model.Comment; + +/** + * + * @author OS + */ +public class updateCommentServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST methods. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet updateCommentServlet"); + out.println(""); + out.println(""); + out.println("

Servlet updateCommentServlet at " + request.getContextPath () + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("application/json"); + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null){ + String newComment = request.getParameter("newCommentText"); + int commentId = Integer.parseInt(request.getParameter("commentId")); + if(!newComment.trim().isEmpty()){ + Comment comment = new Comment(); + comment.setComment_id(commentId); + comment.setComment_text(newComment); + postDAO PostDao = new postDAO(); + try { + PostDao.updateComment(comment); + response.getWriter().write("{\"success\": true}"); + } catch (Exception e) { + e.printStackTrace(); + response.getWriter().write("{\"success\": false}"); + } + } else { + response.getWriter().write("{\"success\": false}"); + } + } else { + response.getWriter().write("{\"success\": false}"); + } + } + + /** + * Returns a short description of the servlet. + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/updateLearningMaterial.java b/src/java/controller/updateLearningMaterial.java new file mode 100644 index 0000000..9fd0a82 --- /dev/null +++ b/src/java/controller/updateLearningMaterial.java @@ -0,0 +1,153 @@ +package controller; + +import com.dropbox.core.DbxException; +import com.dropbox.core.DbxRequestConfig; +import com.dropbox.core.v2.DbxClientV2; +import com.dropbox.core.v2.files.WriteMode; +import dao.learningMaterialDao; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.MultipartConfig; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.Part; +import java.util.Date; +import java.util.logging.Level; +import java.util.logging.Logger; +import model.LearningMaterial; +import model.User; + +@MultipartConfig +public class updateLearningMaterial extends HttpServlet { + + private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(updateLearningMaterial.class.getName()); + + private static final String ACCESS_TOKEN = "sl.B_oVGLZBc_ZXr3lMWjy6DxIkooVzryaLCDrIp-mFaw3mFLxWlIqpC_vM1GYdC9t8A8XaevphHfLB_kuu5wTp_suI_wNCVWdDdFL6ldE37u2tB8ilYGFjuOLAsJqqgNfAlD9ctkXBGLzD2yieqHJmkPo"; + private DbxClientV2 client; + + @Override + public void init() throws ServletException { + logger.info("Initializing Dropbox client..."); + DbxRequestConfig config = DbxRequestConfig.newBuilder("dropbox/java-tutorial").build(); + client = new DbxClientV2(config, ACCESS_TOKEN); + logger.info("Dropbox client initialized."); + } + + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet updateLearningMaterial"); + out.println(""); + out.println(""); + out.println("

Servlet updateLearningMaterial at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + request.setCharacterEncoding("UTF-8"); + learningMaterialDao dao = new learningMaterialDao(); + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + logger.info("User session found. Proceeding with file upload."); + User user = (User) session.getAttribute("user"); + int userId = user.getUser_id(); + + int learningMaterialId = Integer.parseInt(request.getParameter("id")); + String name = request.getParameter("name"); + String description = request.getParameter("description"); + if (description == null) { + response.sendRedirect("lmaterialLink"); + return; + } + Part filePart = request.getPart("context"); + String context = getFileName(filePart); + String subjectCode = request.getParameter("subjectCode"); + String departmentIdStr = request.getParameter("departmentId"); + String review = request.getParameter("review"); + + try { + if (filePart != null && filePart.getSize() > 0) { + InputStream inputStream = filePart.getInputStream(); + logger.log(Level.INFO, "Uploading file to Dropbox: {0}", context); + client.files().uploadBuilder("/" + context) + .withMode(WriteMode.OVERWRITE) + .uploadAndFinish(inputStream); + logger.info("File uploaded successfully."); + } + else { + LearningMaterial lm=dao.getLearningMaterialById(learningMaterialId); + context=lm.getLearningMaterialContext(); + } + + } catch (DbxException | IOException e) { + logger.info("Error uploading file to Dropbox"); + response.sendRedirect("lmaterialLink"); + return; + } catch (Exception ex) { + Logger.getLogger(updateLearningMaterial.class.getName()).log(Level.SEVERE, null, ex); + } + + int departmentId; + try { + departmentId = Integer.parseInt(departmentIdStr); + logger.info("Parsed department ID: " + departmentId); + } catch (NumberFormatException e) { + response.sendRedirect("lmaterialLink"); + return; + } + + Date publishDate = new Date(); + + LearningMaterial learningMaterial = new LearningMaterial(learningMaterialId, userId, name, description, context, subjectCode, publishDate, review, departmentId); + + + try { + dao.updateLearningMaterial(learningMaterial); + logger.info("Learning material updated successfully."); + request.setAttribute("successMessage", "Learning Material updated successfully"); + response.sendRedirect("lmaterialLink"); + } catch (Exception e) { + e.printStackTrace(); + request.setAttribute("errorMessage", "Error updating learning material"); + response.sendRedirect("lmaterialLink"); + } + } else { + response.sendRedirect("login.jsp"); // Redirect to login page if user is not logged in + } + } + + private String getFileName(Part part) { + String contentDisp = part.getHeader("content-disposition"); + String[] tokens = contentDisp.split(";"); + + for (String token : tokens) { + if (token.trim().startsWith("filename")) { + return token.substring(token.indexOf("=") + 2, token.length() - 1); + } + } + return ""; + } + + @Override + public String getServletInfo() { + return "Short description"; + } +} \ No newline at end of file diff --git a/src/java/controller/updatePostServlet.java b/src/java/controller/updatePostServlet.java new file mode 100644 index 0000000..ccd50f2 --- /dev/null +++ b/src/java/controller/updatePostServlet.java @@ -0,0 +1,234 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.MultipartConfig; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.Part; +import java.io.File; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import model.Post; +import model.User; + +/** + * + * @author OS + */ +@MultipartConfig( + fileSizeThreshold = 1024 * 1024 * 2, // 2MB + maxFileSize = 1024 * 1024 * 50, // 50MB + maxRequestSize = 1024 * 1024 * 100 // 100MB +) +public class updatePostServlet extends HttpServlet { + + private static final Logger LOGGER = Logger.getLogger(updatePostServlet.class.getName()); + + private static final long serialVersionUID = 1L; + + private static final Set ALLOWED_IMAGE_TYPES = new HashSet<>(Arrays.asList( + "image/jpeg", "image/png", "image/gif", "image/bmp", "image/webp" + )); + + private static final Set ALLOWED_VIDEO_TYPES = new HashSet<>(Arrays.asList( + "video/mp4", "video/mpeg", "video/quicktime", "video/x-msvideo", "video/webm" + )); + + Cloudinary cloud; + + public void init() throws ServletException { + Properties properties = new Properties(); + String propFileName = "/WEB-INF/cloudinary.properties.txt"; + InputStream inputStream = getServletContext().getResourceAsStream(propFileName); + if (inputStream == null) { + throw new ServletException("Property file '" + propFileName + "' not found in classpath"); + } + try { + properties.load(inputStream); + } catch (IOException ex) { + Logger.getLogger(postServlet.class.getName()).log(Level.SEVERE, null, ex); + } + String cloudName = properties.getProperty("cloud_name"); + String apiKey = properties.getProperty("api_key"); + String apiSecret = properties.getProperty("api_secret"); + try { + cloud = new Cloudinary(ObjectUtils.asMap( + "cloud_name", cloudName, + "api_key", apiKey, + "api_secret", apiSecret + )); + } catch (Exception e) { + throw new ServletException("Failed to initialize Cloudinary", e); + } + } + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet updatePostServlet"); + out.println(""); + out.println(""); + out.println("

Servlet updatePostServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + LOGGER.info("Starting to process post update request"); + try { + String newBody = request.getParameter("newBody"); + Part filePart = request.getPart("newImage"); + int postId = Integer.parseInt(request.getParameter("postId")); + String resourceType = null; + if (filePart == null) { + LOGGER.warning("No file part found in request"); + + } + + postDAO PostDao = new postDAO(); + Post post = PostDao.getPostById(postId); + LOGGER.log(Level.INFO, "Updating post with ID: {0}", postId); + if (post == null) { + LOGGER.warning("Post not found with ID: " + postId); + session.setAttribute("errorMessage", "Post not found"); + response.sendRedirect("profile"); + return; + } + + if (newBody != null && !newBody.trim().isEmpty()) { + post.setBody(newBody); + } + + if (filePart != null && filePart.getSize() > 0) { + String contentType = filePart.getContentType(); + LOGGER.info("File upload detected with content type: " + contentType); + if (!ALLOWED_IMAGE_TYPES.contains(contentType) && !ALLOWED_VIDEO_TYPES.contains(contentType)) { + LOGGER.warning("Unsupported file type attempted: " + contentType); + request.setAttribute("error", "Unsupported file type"); + response.sendRedirect("profile"); + return; + } + resourceType = ALLOWED_IMAGE_TYPES.contains(contentType) ? "image" : "video"; + try { + LOGGER.info("Starting file upload process"); + File tempFile = File.createTempFile("upload_", filePart.getSubmittedFileName()); + + try (InputStream inputStream = filePart.getInputStream(); FileOutputStream outputStream = new FileOutputStream(tempFile)) { + byte[] buffer = new byte[8192]; + int bytesRead; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead); + } + } + + Map uploadResult = cloud.uploader().upload(tempFile, ObjectUtils.asMap( + "resource_type", resourceType + )); + String imageUrl = (String) uploadResult.get("url"); + post.setImage_path(imageUrl); + post.setType(resourceType); + LOGGER.info("File upload with type "+ resourceType); + LOGGER.info("File uploaded successfully to Cloudinary"); + Files.deleteIfExists(tempFile.toPath()); + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Error uploading file", e); + e.printStackTrace(); + session.setAttribute("errorMessage", "Error uploading image"); + //response.sendRedirect("profile"); + return; + } + } + + PostDao.updatePost(post); + session.setAttribute("successMessage", "Post updated successfully"); + LOGGER.info("Post updated successfully"); + response.setContentType("text/plain"); + response.getWriter().write("success"); + // response.sendRedirect("profile"); + + } catch (Exception e) { + e.printStackTrace(); + LOGGER.log(Level.SEVERE, "Error in doPost method", e); + session.setAttribute("errorMessage", "Error updating post: " + e.getMessage()); + response.setContentType("text/plain"); + response.getWriter().write("error: Invalid post ID"); + // response.sendRedirect("profile"); + } + } else { + response.sendRedirect("profile"); + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/updatePrivateServlet.java b/src/java/controller/updatePrivateServlet.java new file mode 100644 index 0000000..07a6be8 --- /dev/null +++ b/src/java/controller/updatePrivateServlet.java @@ -0,0 +1,90 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import dao.postDAO; +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * + * @author OS + */ +public class updatePrivateServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet updatePrivateServlet"); + out.println(""); + out.println(""); + out.println("

Servlet updatePrivateServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + int postId = Integer.parseInt(request.getParameter("postId")); + String privacyMode = request.getParameter("privacyMode"); + postDAO postDao = new postDAO(); + postDao.updatePostPrivacy(postId, privacyMode); + response.sendRedirect("profile"); + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/userIntroduceServlet.java b/src/java/controller/userIntroduceServlet.java new file mode 100644 index 0000000..4c7a4cb --- /dev/null +++ b/src/java/controller/userIntroduceServlet.java @@ -0,0 +1,104 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template + */ +package controller; + +import java.io.IOException; +import java.io.PrintWriter; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; +import model.User; +import dao.userDAO; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author bim26 + */ +public class userIntroduceServlet extends HttpServlet { + + /** + * Processes requests for both HTTP GET and POST + * methods. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + protected void processRequest(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html;charset=UTF-8"); + try (PrintWriter out = response.getWriter()) { + /* TODO output your page here. You may use following sample code. */ + out.println(""); + out.println(""); + out.println(""); + out.println("Servlet userIntroduceServlet"); + out.println(""); + out.println(""); + out.println("

Servlet userIntroduceServlet at " + request.getContextPath() + "

"); + out.println(""); + out.println(""); + } + } + + // + /** + * Handles the HTTP GET method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + processRequest(request, response); + } + + /** + * Handles the HTTP POST method. + * + * @param request servlet request + * @param response servlet response + * @throws ServletException if a servlet-specific error occurs + * @throws IOException if an I/O error occurs + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + HttpSession session = request.getSession(false); + if (session != null && session.getAttribute("user") != null) { + User user = (User) session.getAttribute("user"); + String newIntroduction = request.getParameter("userIntro"); + if (newIntroduction != null && !newIntroduction.trim().isEmpty()) { + userDAO.getInstance().updateUserIntroduction(user.getUser_id(), newIntroduction); + user.setUser_introduce(newIntroduction); + response.sendRedirect("profile"); + } else { + response.sendRedirect("profile"); + } + } else { + response.sendRedirect("login"); + } + } + + /** + * Returns a short description of the servlet. + * + * @return a String containing servlet description + */ + @Override + public String getServletInfo() { + return "Short description"; + }// + +} diff --git a/src/java/controller/userpageServlet.java b/src/java/controller/userpageServlet.java index 72ca951..c92a70d 100644 --- a/src/java/controller/userpageServlet.java +++ b/src/java/controller/userpageServlet.java @@ -53,6 +53,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t request.getRequestDispatcher("error.jsp").forward(request, response); return; } + String introduction = userDao.getUserIntroduce(user.getUser_id()); + user.setUser_introduce(introduction); } catch (SQLException ex) { Logger.getLogger(userpageServlet.class.getName()).log(Level.SEVERE, "Error fetching user", ex); request.setAttribute("errorMessage", "Error fetching user data"); @@ -83,14 +85,13 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) t request.setAttribute("friendCount", friendCount); } catch (Exception e) { Logger.getLogger(userpageServlet.class.getName()).log(Level.SEVERE, "Error fetching friends", e); - // We'll continue even if friends can't be fetched + } request.setAttribute("user", user); request.setAttribute("posts", posts); request.getRequestDispatcher("/WEB-INF/profile.jsp").forward(request, response); } - @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); @@ -100,12 +101,10 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) Part file = request.getPart("image"); String image_path = file.getSubmittedFileName(); - String uploadPath = "E:/FUNET/FUNET/web/assets/profile_avt/" + image_path; - //E:\FUNET\FUNET\web\assets + String uploadPath = getServletContext().getRealPath("/assets/post_image/") + image_path; try { FileOutputStream fos = new FileOutputStream(uploadPath); InputStream is = file.getInputStream(); - byte[] data = new byte[is.available()]; is.read(data); fos.write(data); diff --git a/src/java/dao/AdminDAO.java b/src/java/dao/AdminDAO.java new file mode 100644 index 0000000..34a5cd7 --- /dev/null +++ b/src/java/dao/AdminDAO.java @@ -0,0 +1,36 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package dao; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import model.Month; +import util.sqlConnect; +/** + * + * @author Quocb + */ +public class AdminDAO { + public boolean updateUserBanStatus(int userId, boolean isBanned) { + String sql = "UPDATE userAccount SET is_banned = ? WHERE user_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); + PreparedStatement ps = conn.prepareStatement(sql)) { + ps.setBoolean(1, isBanned); + ps.setInt(2, userId); + int rowsUpdated = ps.executeUpdate(); + return rowsUpdated > 0; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public static void main(String[] args) { + AdminDAO dao=new AdminDAO(); + dao.updateUserBanStatus(1, true); + } + +} diff --git a/src/java/dao/ConversationDAO.java b/src/java/dao/ConversationDAO.java index f0734dd..91942cf 100644 --- a/src/java/dao/ConversationDAO.java +++ b/src/java/dao/ConversationDAO.java @@ -4,19 +4,21 @@ */ package dao; +import controller.ConversationRestController; import java.util.List; import model.Conversation; import model.User; import util.sqlConnect; import java.sql.*; import java.util.ArrayList; +import java.util.logging.Logger; /** * * @author HELLO */ public class ConversationDAO { - +private static final Logger LOGGER = Logger.getLogger(ConversationDAO.class.getName()); /** * @param args the command line arguments */ @@ -34,26 +36,29 @@ public synchronized static ConversationDAO getInstance() { } public void saveConversation(Conversation conversation, List users) throws Exception { - if (conversation == null) { + if (users == null) { return; - } - - Connection conn = sqlConnect.getInstance().getConnection(); - try { - if (conversation.getId() == 0) { - createNewConversation(conn, conversation, users); - } else { - updateConversation(conn, conversation); + } else { + Connection conn = sqlConnect.getInstance().getConnection(); + try { + if (conversation.getId() == 0) { + createNewConversation(conn, conversation, users); + } else { + for (User user : users) { + addUserToConversation(conn, conversation.getId(), user); + } + } + } finally { } - } finally { - conn.close(); } } private void createNewConversation(Connection conn, Conversation conversation, List users) throws Exception { - String createConversationSQL = "INSERT INTO conversation(conversation_name, conversation_avatar) VALUES(?, CONCAT('group-', CAST(IDENT_CURRENT('conversation') AS CHAR(50))))"; +// CONCAT('group-', CAST(IDENT_CURRENT('conversation') AS CHAR(50))) + String createConversationSQL = "INSERT INTO conversation(conversation_name, conversation_avatar) VALUES(?, ?)"; PreparedStatement st = conn.prepareStatement(createConversationSQL, PreparedStatement.RETURN_GENERATED_KEYS); st.setString(1, conversation.getName()); + st.setString(2, "assets/group/group1/group2.jpg"); st.executeUpdate(); ResultSet rs = st.getGeneratedKeys(); if (rs.next()) { @@ -76,13 +81,23 @@ private void addUserToConversation(Connection conn, int conversationId, User use st.executeUpdate(); } - private void updateConversation(Connection conn, Conversation conversation) throws Exception { - String updateSQL = "UPDATE conversation SET conversation_name=?, conversation_avatar=? WHERE conversation_id=?"; - PreparedStatement st = conn.prepareStatement(updateSQL); - st.setString(1, conversation.getName()); - st.setString(2, conversation.getAvatar().replaceAll(" ", "")); - st.setInt(3, conversation.getId()); - st.executeUpdate(); + public void updateConversation(Conversation conversation) throws Exception { + Connection conn = sqlConnect.getInstance().getConnection(); + LOGGER.info("update request"); + if (conversation.getAvatar() == null) { + String updateSQL = "UPDATE conversation SET conversation_name=? WHERE conversation_id=?"; + PreparedStatement st = conn.prepareStatement(updateSQL); + st.setString(1, conversation.getName()); + st.setInt(2, conversation.getId()); + st.executeUpdate(); + } else { + LOGGER.info("perform change avatar with: " + conversation.getId() + " " + conversation.getAvatar()); + String updateSQL = "UPDATE conversation SET conversation_avatar=? WHERE conversation_id=?"; + PreparedStatement st = conn.prepareStatement(updateSQL); + st.setString(1, conversation.getAvatar()); + st.setInt(2, conversation.getId()); + st.executeUpdate(); + } } public List findAllConversationsByUserId(int userId) throws Exception { @@ -98,7 +113,6 @@ public List findAllConversationsByUserId(int userId) throws Except Conversation conversation = new Conversation(rs.getInt("conversation_id"), rs.getString("conversation_name"), rs.getString("conversation_avatar")); conversations.add(conversation); } - conn.close(); return conversations; } @@ -112,7 +126,6 @@ public Conversation findConversationById(int id) throws Exception { if (rs.next()) { conversation = new Conversation(rs.getInt("conversation_id"), rs.getString("conversation_name"), rs.getString("conversation_avatar")); } - conn.close(); return conversation; } @@ -128,7 +141,6 @@ public void deleteConversationById(int id) throws Exception { st.setInt(3, id); st.executeUpdate(); } finally { - conn.close(); } } @@ -139,7 +151,6 @@ public void deleteUserFromConversation(int conversationId, int userId) throws Ex st.setInt(1, conversationId); st.setInt(2, userId); st.executeUpdate(); - conn.close(); } public List findConversationsOfUserByKeyword(int userId, String keyword) throws Exception { @@ -156,11 +167,13 @@ public List findConversationsOfUserByKeyword(int userId, String ke Conversation conversation = new Conversation(rs.getInt("conversation_id"), rs.getString("conversation_name"), rs.getString("conversation_avatar")); conversations.add(conversation); } - conn.close(); return conversations; } - + public static void main(String[] args) throws Exception { - ConversationDAO.getInstance().findAllConversationsByUserId(1); + List list = ConversationDAO.getInstance().findAllConversationsByUserId(1); + for (Conversation conversation : list) { + System.out.println(conversation.getId()); + } } } diff --git a/src/java/dao/FriendDAO.java b/src/java/dao/FriendDAO.java index a434da2..02a6589 100644 --- a/src/java/dao/FriendDAO.java +++ b/src/java/dao/FriendDAO.java @@ -101,8 +101,8 @@ public String checkFriendStatus(int currUser, int responUser) throws Exception { PreparedStatement ps = conn.prepareStatement("SELECT * FROM friendship WHERE (sender = ? AND receiver=?) OR (sender = ? AND receiver = ?)"); ps.setInt(1, currUser); ps.setInt(2, responUser); - ps.setInt(3, currUser); - ps.setInt(4, responUser); + ps.setInt(3, responUser); + ps.setInt(4, currUser); try (ResultSet rs = ps.executeQuery()) { while (rs.next()) { diff --git a/src/java/dao/MessageDao.java b/src/java/dao/MessageDao.java index 5de30d2..3ddb74c 100644 --- a/src/java/dao/MessageDao.java +++ b/src/java/dao/MessageDao.java @@ -90,7 +90,7 @@ public void saveMessage(Message message) throws Exception { int conversations_id = message.getGroupId(); PreparedStatement stmt = null; - // If it's a one-on-one message (sender and receiver) + // If it's a one-to-one message (sender and receiver) if (receiver != 0) { String query = "INSERT INTO message(sender, receiver, message_text, message_type) VALUES(?,?,?,?)"; stmt = conn.prepareStatement(query); @@ -100,12 +100,12 @@ public void saveMessage(Message message) throws Exception { stmt.setString(4, type); } // If it's a group message (sender and group) else { - String query = "INSERT INTO message(sender, message_text, message_type, conversations_id) VALUES(?,?,?,?)"; + String query = "INSERT INTO message(sender, conversation_id, message_text, message_type) VALUES(?,?,?,?)"; stmt = conn.prepareStatement(query); stmt.setInt(1, sender); - stmt.setString(2, msg); - stmt.setString(3, type); - stmt.setInt(4, conversations_id); + stmt.setInt(2, conversations_id); + stmt.setString(3, msg); + stmt.setString(4, type); } // Execute the insert statement @@ -114,5 +114,8 @@ public void saveMessage(Message message) throws Exception { // Close resources stmt.close(); } - + public static void main(String[] args) throws Exception { + List msg = MessageDao.getInstance().findAllMessagesBySenderAndReceiver(1, 2); + System.out.println(msg.get(1).getMessage()); + } } diff --git a/src/java/dao/MonthDAO.java b/src/java/dao/MonthDAO.java new file mode 100644 index 0000000..36ea5ed --- /dev/null +++ b/src/java/dao/MonthDAO.java @@ -0,0 +1,95 @@ +package dao; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import model.Month; +import util.sqlConnect; + +public class MonthDAO { + public List Get7Month() { + List results = new ArrayList<>(); + String sql = "WITH LastSevenMonths AS (" + + " SELECT " + + " DATEADD(MONTH, number, DATEADD(MONTH, -7, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))) AS MonthStart " + + " FROM master.dbo.spt_values " + + " WHERE type = 'P' AND number <= 6 " + + "), " + + "MonthlyRegistrations AS (" + + " SELECT " + + " DATEADD(MONTH, DATEDIFF(MONTH, 0, created_at), 0) AS MonthStart," + + " COUNT(*) AS RegistrationCount " + + " FROM " + + " userAccount " + + " WHERE " + + " created_at >= DATEADD(MONTH, -7, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) " + + " AND created_at < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) " + + " GROUP BY " + + " DATEADD(MONTH, DATEDIFF(MONTH, 0, created_at), 0) " + + ") " + + "SELECT " + + " DATENAME(MONTH, m.MonthStart) AS MonthName, " + + " ISNULL(r.RegistrationCount, 0) AS RegistrationCount " + + "FROM " + + " LastSevenMonths m " + + " LEFT JOIN MonthlyRegistrations r ON m.MonthStart = r.MonthStart " + + "ORDER BY " + + " m.MonthStart ASC"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); + PreparedStatement stmt = conn.prepareStatement(sql)) { + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + String monthName = rs.getString("MonthName"); + int count = rs.getInt("RegistrationCount"); + results.add(new Month(monthName, count)); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return results; + } + + public Month getLastMonthRegistrationCountAndName() { + String sql = "SELECT ISNULL(COUNT(*), 0) AS registration_count, " + + "DATENAME(MONTH, DATEADD(MONTH, -1, GETDATE())) AS month_name " + + "FROM userAccount WHERE " + + "created_at >= DATEADD(MONTH, -1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) " + + "AND created_at < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); + PreparedStatement stmt = conn.prepareStatement(sql)) { + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int count = rs.getInt("registration_count"); + String monthName = rs.getString("month_name"); + return new Month(monthName, count); + } + } catch (SQLException e) { + e.printStackTrace(); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public static void main(String[] args) { + MonthDAO dao = new MonthDAO(); + // Kiểm tra Get7Month + System.out.println("Get7Month Results:"); + List list = dao.Get7Month(); + for (Month a : list) { + System.out.println(a); + } + + // Kiểm tra getLastMonthRegistrationCountAndName + System.out.println("\nLast Month Registration Count and Name:"); + Month lastMonth = dao.getLastMonthRegistrationCountAndName(); + if (lastMonth != null) { + System.out.println(lastMonth); + } else { + System.out.println("No data found for the last month."); + } + } +} diff --git a/src/java/dao/SearchGameDAO.java b/src/java/dao/SearchGameDAO.java new file mode 100644 index 0000000..9e936e3 --- /dev/null +++ b/src/java/dao/SearchGameDAO.java @@ -0,0 +1,52 @@ +package dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import model.game; +import util.sqlConnect; + +public class SearchGameDAO { + + public List searchGameByKeyword(String keyword) { + List list = new ArrayList<>(); + String sql = "SELECT G.GameID, G.GameName, G.GameLink,G.Img , T.CategoryName " + + "FROM Game G " + + "JOIN GameCategory T ON G.CategoryID = T.CategoryID " + + "WHERE G.GameName LIKE ?"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + + stmt.setString(1, "%" + keyword + "%"); + + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + game game = new game( + rs.getInt("GameID"), + rs.getString("GameName"), + rs.getString("GameLink"), + rs.getString("Img"), + rs.getString("CategoryName") + ); + list.add(game); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return list; + } + + public static void main(String[] args) { + SearchGameDAO dao = new SearchGameDAO(); + List games = dao.searchGameByKeyword("a"); + for (game game : games) { + System.out.println(game); + } + } +} diff --git a/src/java/dao/UserActivityDAO.java b/src/java/dao/UserActivityDAO.java new file mode 100644 index 0000000..98f7c26 --- /dev/null +++ b/src/java/dao/UserActivityDAO.java @@ -0,0 +1,133 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package dao; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import model.UserActivityLog; +import util.sqlConnect; + +/** + * + * @author Quocb + */ +public class UserActivityDAO { + + public List getUserActivities(int userId) { + List activities = new ArrayList<>(); + String sql = "SELECT * FROM UserActivityLog ul JOIN userAccount u ON ul.user_id=u.user_id WHERE u.user_id = ? ORDER BY timestamp DESC"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + + stmt.setInt(1, userId); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + UserActivityLog log = new UserActivityLog(); + log.setLogId(rs.getInt("log_id")); + log.setUserId(rs.getInt("user_id")); + log.setRole(rs.getString("role")); + log.setFirstName(rs.getString("first_name")); + log.setLastName(rs.getString("last_name")); + log.setPostId(rs.getInt("post_id")); + log.setCommentId(rs.getInt("comment_id")); + log.setActivityType(rs.getString("activity_type")); + log.setActivityDetails(rs.getString("activity_details")); + log.setTimestamp(rs.getTimestamp("timestamp").toLocalDateTime()); + activities.add(log); + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return activities; + } + + public List geAlltUserActivities() { + List activities = new ArrayList<>(); + String sql = "SELECT * FROM UserActivityLog ul JOIN userAccount u ON ul.user_id=u.user_id ORDER BY timestamp DESC"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + UserActivityLog log = new UserActivityLog(); + log.setLogId(rs.getInt("log_id")); + log.setUserId(rs.getInt("user_id")); + log.setRole(rs.getString("role")); + log.setFirstName(rs.getString("first_name")); + log.setLastName(rs.getString("last_name")); + log.setPostId(rs.getInt("post_id")); + log.setCommentId(rs.getInt("comment_id")); + log.setActivityType(rs.getString("activity_type")); + log.setActivityDetails(rs.getString("activity_details")); + log.setTimestamp(rs.getTimestamp("timestamp").toLocalDateTime()); + activities.add(log); + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return activities; + } + + public void deleteUserActivityById(int logId) { + String sql = "DELETE FROM UserActivityLog WHERE log_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + + stmt.setInt(1, logId); + int rowsAffected = stmt.executeUpdate(); + + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + + } + } + + public void deleteUserActivityByCommentId(int commentId) { + String sql = "DELETE FROM UserActivityLog WHERE comment_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + + stmt.setInt(1, commentId); + int rowsAffected = stmt.executeUpdate(); + + + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + + } + } + + public void deleteUserActivityByPostId(int postId) { + String sql = "DELETE FROM UserActivityLog WHERE post_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + + stmt.setInt(1, postId); + int rowsAffected = stmt.executeUpdate(); + + + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) { + UserActivityDAO dao = new UserActivityDAO(); + List a = dao.geAlltUserActivities(); + for (UserActivityLog s : a) { + System.out.println(s); + } + } + +} diff --git a/src/java/dao/gameDAO.java b/src/java/dao/gameDAO.java new file mode 100644 index 0000000..99026fa --- /dev/null +++ b/src/java/dao/gameDAO.java @@ -0,0 +1,48 @@ +package dao; + +import model.game; +import util.sqlConnect; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class gameDAO { + public List getAllGames() { + List games = new ArrayList<>(); + String sql = "SELECT G.GameID, G.GameName, G.GameLink,G.Img, T.CategoryName " + + "FROM Game G " + + "JOIN GameCategory T ON G.CategoryID = T.CategoryID"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); + PreparedStatement stmt = conn.prepareStatement(sql); + ResultSet rs = stmt.executeQuery()) { + + while (rs.next()) { + game Game = new game( + rs.getInt("GameID"), + rs.getString("GameName"), + rs.getString("GameLink"), + rs.getString("Img"), + rs.getString("CategoryName") + ); + games.add(Game); + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return games; + } + + public static void main(String[] args) { + gameDAO dao = new gameDAO(); + List games = dao.getAllGames(); + for (game game : games) { + System.out.println(game); + } + } +} diff --git a/src/java/dao/learningMaterialDao.java b/src/java/dao/learningMaterialDao.java index 1d2fcbf..b71d006 100644 --- a/src/java/dao/learningMaterialDao.java +++ b/src/java/dao/learningMaterialDao.java @@ -1,50 +1,233 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ package dao; +/** + * + * @author gabri + */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Date; import java.util.List; import model.LearningMaterial; import util.sqlConnect; public class learningMaterialDao { + public List getAll() throws Exception { - List learningMaterialsList = new ArrayList<>(); - - String sql = "SELECT * FROM learningmaterial"; - - try (Connection conn = sqlConnect.getInstance().getConnection(); - PreparedStatement preparedStatement = conn.prepareStatement(sql); - ResultSet resultSet = preparedStatement.executeQuery()) { - // ket noi sql va lay thong tin learningmaterial ra khoi sql + String sql = "SELECT * FROM learningmaterial"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery()) { while (resultSet.next()) { int learningMaterialId = resultSet.getInt("learningmaterial_id"); int userId = resultSet.getInt("user_id"); String learningmaterialName = resultSet.getString("learningmaterial_name"); String learningmaterialDescription = resultSet.getString("learningmaterial_description"); - String learningmaterialImg = resultSet.getString("learningmaterial_img"); String learningmaterialContext = resultSet.getString("learningmaterial_context"); String subjectCode = resultSet.getString("subject_code"); - java.util.Date publishDate = resultSet.getDate("publish_date"); - - // luu learningmaterial vao list learning material - LearningMaterial learningMaterial = new LearningMaterial(learningMaterialId, userId, learningmaterialName, learningmaterialDescription, learningmaterialImg, learningmaterialContext, subjectCode, publishDate, ""); + String review = resultSet.getString("review"); + int departmentId = resultSet.getInt("department_id"); + + LearningMaterial learningMaterial = new LearningMaterial(learningMaterialId, userId, learningmaterialName, learningmaterialDescription, learningmaterialContext, subjectCode, publishDate, review, departmentId); learningMaterialsList.add(learningMaterial); + } + } catch (SQLException e) { + e.printStackTrace(); + } + + return learningMaterialsList; + } + + public LearningMaterial getLearningMaterialById(int learningMaterialId) throws SQLException, Exception { + String sql = "SELECT * FROM learningmaterial WHERE learningmaterial_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, learningMaterialId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int userId = rs.getInt("user_id"); + String learningMaterialName = rs.getString("learningmaterial_name"); + String learningMaterialDescription = rs.getString("learningmaterial_description"); + String learningMaterialContext = rs.getString("learningmaterial_context"); + String subjectCode = rs.getString("subject_code"); + Date publishDate = rs.getDate("publish_date"); + String review = rs.getString("review"); + int departmentId = rs.getInt("department_id"); + + return new LearningMaterial(learningMaterialId, userId, learningMaterialName, learningMaterialDescription, learningMaterialContext, subjectCode, publishDate, review, departmentId); } + } + } catch (SQLException e) { + e.printStackTrace(); + throw new Exception("Error retrieving learning material", e); + } + return null; + } + public List searchLearningMaterials(String keyword) throws Exception { + List learningMaterialsList = new ArrayList<>(); + String sql = "SELECT * FROM learningmaterial WHERE learningmaterial_name LIKE ? OR learningmaterial_description LIKE ? OR subject_code LIKE ?"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { + preparedStatement.setString(1, "%" + keyword + "%"); + preparedStatement.setString(2, "%" + keyword + "%"); + preparedStatement.setString(3, "%" + keyword + "%"); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + while (resultSet.next()) { + int learningMaterialId = resultSet.getInt("learningmaterial_id"); + int userId = resultSet.getInt("user_id"); + String learningmaterialName = resultSet.getString("learningmaterial_name"); + String learningmaterialDescription = resultSet.getString("learningmaterial_description"); + String learningmaterialContext = resultSet.getString("learningmaterial_context"); + String subjectCode = resultSet.getString("subject_code"); + java.util.Date publishDate = resultSet.getDate("publish_date"); + String review = resultSet.getString("review"); + int departmentId = resultSet.getInt("department_id"); + + LearningMaterial learningMaterial = new LearningMaterial(learningMaterialId, userId, learningmaterialName, learningmaterialDescription, learningmaterialContext, subjectCode, publishDate, review, departmentId); + learningMaterialsList.add(learningMaterial); + } + } } catch (SQLException e) { e.printStackTrace(); } - + return learningMaterialsList; } - - public static void main(String[] args) throws Exception { - learningMaterialDao leMaterialDao = new learningMaterialDao(); - System.out.println(leMaterialDao.getAll()); + + public List getByDepartment(int departmentId) throws Exception { + List learningMaterialsList = new ArrayList<>(); + String sql = "SELECT * FROM learningmaterial WHERE department_id = ?"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement preparedStatement = conn.prepareStatement(sql)) { + preparedStatement.setInt(1, departmentId); + try (ResultSet resultSet = preparedStatement.executeQuery()) { + while (resultSet.next()) { + int learningMaterialId = resultSet.getInt("learningmaterial_id"); + int userId = resultSet.getInt("user_id"); + String learningmaterialName = resultSet.getString("learningmaterial_name"); + String learningmaterialDescription = resultSet.getString("learningmaterial_description"); + String learningmaterialContext = resultSet.getString("learningmaterial_context"); + String subjectCode = resultSet.getString("subject_code"); + java.util.Date publishDate = resultSet.getDate("publish_date"); + String review = resultSet.getString("review"); + int departmentIdResult = resultSet.getInt("department_id"); + + LearningMaterial learningMaterial = new LearningMaterial(learningMaterialId, userId, learningmaterialName, learningmaterialDescription, learningmaterialContext, subjectCode, publishDate, review, departmentIdResult); + learningMaterialsList.add(learningMaterial); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + + return learningMaterialsList; + } + + public void createLearningMaterial(LearningMaterial learningMaterial) throws SQLException, Exception { + String sql = "INSERT INTO learningmaterial (user_id, learningmaterial_name, learningmaterial_description, learningmaterial_context, subject_code, publish_date, review, department_id) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, learningMaterial.getUserId()); + stmt.setString(2, learningMaterial.getLearningMaterialName()); + stmt.setString(3, learningMaterial.getLearningMaterialDescription()); + stmt.setString(4, learningMaterial.getLearningMaterialContext()); + stmt.setString(5, learningMaterial.getSubjectCode()); + stmt.setTimestamp(6, new java.sql.Timestamp(learningMaterial.getPublishDate().getTime())); + stmt.setString(7, learningMaterial.getReview()); + stmt.setInt(8, learningMaterial.getDepartmentId()); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + throw new Exception("Error creating learning material", e); + } + } + + public void updateLearningMaterial(LearningMaterial learningMaterial) throws SQLException, Exception { + String sql = "UPDATE learningmaterial SET learningmaterial_name = ?, learningmaterial_description = ?, learningmaterial_context = ?, subject_code = ?, publish_date = ?, review = ?, department_id = ? WHERE learningmaterial_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setString(1, learningMaterial.getLearningMaterialName()); + stmt.setString(2, learningMaterial.getLearningMaterialDescription()); + stmt.setString(3, learningMaterial.getLearningMaterialContext()); + stmt.setString(4, learningMaterial.getSubjectCode()); + stmt.setTimestamp(5, new java.sql.Timestamp(learningMaterial.getPublishDate().getTime())); + stmt.setString(6, learningMaterial.getReview()); + stmt.setInt(7, learningMaterial.getDepartmentId()); + stmt.setInt(8, learningMaterial.getLearningMaterialId()); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + throw new Exception("Error updating learning material", e); + } +} + + public void deleteLearningMaterial(int learningMaterialId) throws SQLException, Exception { + String sql = "DELETE FROM learningmaterial WHERE learningmaterial_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, learningMaterialId); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + throw new Exception("Error deleting learning material", e); + } } + + public void saveLearningMaterial(int userId, int learningMaterialId) throws SQLException, Exception { + String sql = "INSERT INTO saved_learning_materials (user_id, learning_material_id) VALUES (?, ?)"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, userId); + stmt.setInt(2, learningMaterialId); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + throw new Exception("Error saving learning material", e); + } + } + + public List getSavedLearningMaterials(int userId) throws SQLException, Exception { + List savedMaterials = new ArrayList<>(); + String query = "SELECT lm.learningmaterial_id, lm.user_id, lm.learningmaterial_name, lm.learningmaterial_description, lm.learningmaterial_context, lm.subject_code, lm.publish_date, lm.review, lm.department_id " + + "FROM saved_learning_materials slm " + + "JOIN learningmaterial lm ON slm.learning_material_id = lm.learningmaterial_id " + + "WHERE slm.user_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, userId); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + int learningMaterialId = rs.getInt("learningmaterial_id"); + int userIdDb = rs.getInt("user_id"); + String learningMaterialName = rs.getString("learningmaterial_name"); + String learningMaterialDescription = rs.getString("learningmaterial_description"); + String learningMaterialContext = rs.getString("learningmaterial_context"); + String subjectCode = rs.getString("subject_code"); + Date publishDate = rs.getDate("publish_date"); + String review = rs.getString("review"); + int departmentId = rs.getInt("department_id"); + + LearningMaterial learningMaterial = new LearningMaterial(learningMaterialId, userIdDb, learningMaterialName, learningMaterialDescription, learningMaterialContext, subjectCode, publishDate, review, departmentId); + savedMaterials.add(learningMaterial); + } + } + } catch (SQLException e) { + e.printStackTrace(); + throw new Exception("Error retrieving saved learning materials", e); + } + return savedMaterials; +} + public static void main(String[] args) { + try { + learningMaterialDao dao = new learningMaterialDao(); + List materials = dao.getAll(); + dao.getSavedLearningMaterials(2); + } catch (Exception e) { + e.printStackTrace(); + } + } + } diff --git a/src/java/dao/ordersDAO.java b/src/java/dao/ordersDAO.java index 7149876..dbb6ff2 100644 --- a/src/java/dao/ordersDAO.java +++ b/src/java/dao/ordersDAO.java @@ -8,6 +8,7 @@ import java.sql.*; import java.util.ArrayList; import java.util.List; +import model.OrderDetailDTO; import model.Orders; import util.sqlConnect; /** @@ -186,9 +187,76 @@ public void updateOrderStatus(int orderId, String status) { e.printStackTrace(); } } - + + public List getOrderDetailsForUser(int userId) { + List orderDetails = new ArrayList<>(); + String sql = "SELECT o.order_id, p.product_name, sci.quantity, " + + "p.price * sci.quantity AS total_price, o.order_status, " + + "o.order_date, CONCAT(u.first_name, ' ', u.last_name) AS seller_name " + + "FROM Orders o " + + "JOIN ShoppingCartItem sci ON o.cart_id = sci.cart_id " + + "JOIN Product p ON sci.product_id = p.product_id " + + "JOIN userAccount u ON p.user_id = u.user_id " + + "WHERE o.user_id = ? " + + "ORDER BY o.order_date DESC;"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { + + ps.setInt(1, userId); + ResultSet rs = ps.executeQuery(); + + while (rs.next()) { + OrderDetailDTO detail = new OrderDetailDTO( + rs.getInt("order_id"), + rs.getString("product_name"), + rs.getInt("quantity"), + rs.getDouble("total_price"), + rs.getString("order_status"), + rs.getTimestamp("order_date"), + rs.getString("seller_name") + ); + orderDetails.add(detail); + } + } catch (Exception e) { + e.printStackTrace(); + } + return orderDetails; + } + + public List getOrdersForSeller(int sellerId) throws Exception { + List orderDetails = new ArrayList<>(); + String sql = "SELECT o.order_id, o.order_date, p.product_name, sci.quantity, " + + "p.price, CONCAT(u.first_name, ' ', u.last_name) AS buyer_name " + + "FROM Orders o " + + "JOIN ShoppingCartItem sci ON o.cart_id = sci.cart_id " + + "JOIN Product p ON sci.product_id = p.product_id " + + "JOIN userAccount u ON o.user_id = u.user_id " // Ensure this matches your user table structure + + "WHERE p.user_id = ?"; // Filter by sellerId + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { + stmt.setInt(1, sellerId); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + // Sử dụng constructor với tất cả các tham số + OrderDetailDTO detail = new OrderDetailDTO( + rs.getInt("order_id"), + rs.getString("product_name"), + rs.getInt("quantity"), + rs.getDouble("price"), + "Pending", // Hoặc thay bằng trạng thái đơn hàng thực tế nếu có trong truy vấn + rs.getTimestamp("order_date"), // Chuyển đổi thành Date + rs.getString("buyer_name") // Tên người mua + ); + orderDetails.add(detail); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return orderDetails; + } + public static void main(String[] args) throws Exception { ordersDAO o = new ordersDAO(); - System.out.println(o.getOrdersBySellerProducts(4)); + System.out.println(o.getOrdersForSeller(4)); } -} +} \ No newline at end of file diff --git a/src/java/dao/postDAO.java b/src/java/dao/postDAO.java index 487a490..89ac9df 100644 --- a/src/java/dao/postDAO.java +++ b/src/java/dao/postDAO.java @@ -11,18 +11,36 @@ import java.sql.*; import java.util.ArrayList; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import model.Comment; import model.Post; +import model.UserActivityLog; import util.sqlConnect; public class postDAO { public void addPost(Post p) { - String query = "INSERT INTO post (user_id, body, image_path) VALUES (?, ?, ?)"; + String query = "INSERT INTO post (user_id, body, image_path,type) VALUES (?, ?, ?,?)"; try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, p.getUser_id()); stmt.setString(2, p.getBody()); stmt.setString(3, p.getImage_path()); + stmt.setString(4, p.getType()); + stmt.executeUpdate(); + + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void updatePostPrivacy(int postId, String privacyMode) { + String query = "UPDATE post SET privacy_mode = ? WHERE post_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, privacyMode); + stmt.setInt(2, postId); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); @@ -32,11 +50,12 @@ public void addPost(Post p) { } public void addComment(Comment c) { - String query = "INSERT INTO comment (post_id, user_id, comment_text) VALUES (?, ?, ?)"; + String query = "INSERT INTO comment (post_id, user_id, comment_text, comment_image) VALUES (?, ?, ?, ?)"; try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, c.getPost_id()); stmt.setInt(2, c.getUser_id()); stmt.setString(3, c.getComment_text()); + stmt.setString(4, c.getComment_image()); stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); @@ -130,18 +149,18 @@ public static List getAllPosts(int sessionUserId) { List posts = new ArrayList<>(); try { Connection conn = sqlConnect.getInstance().getConnection(); - - String query = "SELECT DISTINCT p.post_id, p.body, p.post_time, p.user_id, p.image_path, p.like_count, u.first_name, u.last_name, u.profile_pic, " - + "p.is_shared, p.original_post_id, " + String query = "SELECT DISTINCT p.post_id, p.body, p.post_time, p.user_id, p.image_path, p.like_count, p.type, u.first_name, u.last_name, u.profile_pic, " + + "p.is_shared, p.original_post_id, p.privacy_mode, " + "CASE WHEN p.is_shared = 1 THEN CONCAT(op.first_name, ' ', op.last_name) ELSE NULL END AS original_poster_name, " + "CASE WHEN p.is_shared = 1 THEN op.profile_pic ELSE NULL END AS original_poster_avatar, " - + "(SELECT COUNT(*) FROM post_share WHERE post_id = p.post_id) AS share_count " + + "(SELECT COUNT(*) FROM post_share WHERE post_id = p.post_id) AS share_count, " + + "(SELECT COUNT(*) FROM saved_post WHERE user_id = ? AND post_id = p.post_id) AS saved_by_current_user " + "FROM post p " + "JOIN userAccount u ON p.user_id = u.user_id " + "LEFT JOIN post op_post ON p.original_post_id = op_post.post_id " + "LEFT JOIN userAccount op ON op_post.user_id = op.user_id " - + "WHERE p.user_id = ? " - + "OR p.user_id IN ( " + + "WHERE (p.user_id = ? AND p.privacy_mode != 'private') " + + "OR (p.user_id IN ( " + " SELECT CASE " + " WHEN f.sender = ? THEN f.receiver " + " ELSE f.sender " @@ -149,13 +168,15 @@ public static List getAllPosts(int sessionUserId) { + " FROM friendship f " + " WHERE f.status = 'accepted' " + " AND (? IN (f.sender, f.receiver)) " - + ") " + + ") AND p.privacy_mode = 'friend') " + + "OR p.privacy_mode = 'public' " + "ORDER BY p.post_time DESC"; try (PreparedStatement stmt = conn.prepareStatement(query)) { stmt.setInt(1, sessionUserId); stmt.setInt(2, sessionUserId); stmt.setInt(3, sessionUserId); + stmt.setInt(4, sessionUserId); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { @@ -172,9 +193,16 @@ public static List getAllPosts(int sessionUserId) { int originalPostId = rs.getInt("original_post_id"); String originalPosterName = rs.getString("original_poster_name"); int shareCount = rs.getInt("share_count"); + String originalPosterAvatar = rs.getString("original_poster_avatar"); - Post post = new Post(post_id, user_id, body, post_time, first_name, last_name, image_path, profile_pic, like_count, isShared, originalPostId, originalPosterName, shareCount, originalPosterAvatar); + String privacy_mode = rs.getString("privacy_mode"); + boolean savedByCurrentUser = rs.getInt("saved_by_current_user") > 0; + + Post post = new Post(post_id, user_id, body, post_time, first_name, last_name, image_path, profile_pic, like_count, isShared, originalPostId, originalPosterName, shareCount, originalPosterAvatar, privacy_mode); + post.setSavedByCurrentUser(savedByCurrentUser); post.setComments(getComments(post.getPost_id())); + String type = rs.getString("type"); + post.setType(type); posts.add(post); } } @@ -194,7 +222,7 @@ public static List getComments(int postId) { Connection conn = null; PreparedStatement stmt = null; conn = sqlConnect.getInstance().getConnection(); - stmt = conn.prepareStatement("SELECT c.comment_id, c.post_id, c.user_id, c.comment_text, u.first_name, u.last_name, u.profile_pic " + stmt = conn.prepareStatement("SELECT c.comment_id, c.post_id, c.user_id, c.comment_text, c.comment_image, u.first_name, u.last_name, u.profile_pic " + "FROM comment c " + "JOIN userAccount u ON c.user_id = u.user_id " + "WHERE c.post_id = ? " @@ -206,10 +234,11 @@ public static List getComments(int postId) { int post_id = rs.getInt("post_id"); int user_id = rs.getInt("user_id"); String comment_text = rs.getString("comment_text"); + String comment_image = rs.getString("comment_image"); String first_name = rs.getString("first_name"); String last_name = rs.getString("last_name"); String profile_pic = rs.getString("profile_pic"); - Comment comment = new Comment(comment_id, post_id, user_id, first_name, last_name, comment_text, profile_pic); + Comment comment = new Comment(comment_id, post_id, user_id, first_name, last_name, comment_text, profile_pic, comment_image); comments.add(comment); } } catch (SQLException e) { @@ -221,66 +250,55 @@ public static List getComments(int postId) { } public static List getMyPosts(int userId) { - List posts = new ArrayList<>(); - try { - Connection conn = sqlConnect.getInstance().getConnection(); - String query = "SELECT p.post_id, p.body, p.post_time, p.user_id, p.like_count, p.image_path, " - + "u.first_name, u.last_name, u.profile_pic, " - + "p.is_shared, p.original_post_id, " - + "CASE WHEN p.is_shared = 1 THEN CONCAT(op.first_name, ' ', op.last_name) ELSE NULL END AS original_poster_name, " - + "CASE WHEN p.is_shared = 1 THEN op.profile_pic ELSE NULL END AS original_poster_avatar, " - + "(SELECT COUNT(*) FROM post_share WHERE post_id = p.post_id) AS share_count " - + "FROM post p " - + "JOIN userAccount u ON p.user_id = u.user_id " - + "LEFT JOIN post op_post ON p.original_post_id = op_post.post_id " - + "LEFT JOIN userAccount op ON op_post.user_id = op.user_id " - + "WHERE p.user_id = ? " - + "ORDER BY p.post_time DESC"; + List posts = new ArrayList<>(); + try { + Connection conn = sqlConnect.getInstance().getConnection(); + String query = "SELECT p.post_id, p.body, p.post_time, p.user_id, p.like_count,p.type, p.image_path, " + + "u.first_name, u.last_name, u.profile_pic, " + + "p.is_shared, p.original_post_id, " + + "CASE WHEN p.is_shared = 1 THEN CONCAT(op.first_name, ' ', op.last_name) ELSE NULL END AS original_poster_name, " + + "CASE WHEN p.is_shared = 1 THEN op.profile_pic ELSE NULL END AS original_poster_avatar, " + + "(SELECT COUNT(*) FROM post_share WHERE post_id = p.post_id) AS share_count " + + "FROM post p " + + "JOIN userAccount u ON p.user_id = u.user_id " + + "LEFT JOIN post op_post ON p.original_post_id = op_post.post_id " + + "LEFT JOIN userAccount op ON op_post.user_id = op.user_id " + + "WHERE p.user_id = ? " + + "ORDER BY p.post_time DESC"; - try (PreparedStatement stmt = conn.prepareStatement(query)) { - stmt.setInt(1, userId); - try (ResultSet rs = stmt.executeQuery()) { - while (rs.next()) { - int post_id = rs.getInt("post_id"); - int user_id = rs.getInt("user_id"); - String body = rs.getString("body"); - Timestamp post_time = rs.getTimestamp("post_time"); - String first_name = rs.getString("first_name"); - String last_name = rs.getString("last_name"); - int like_count = rs.getInt("like_count"); - String image_path = rs.getString("image_path"); - String profile_pic = rs.getString("profile_pic"); - boolean isShared = rs.getBoolean("is_shared"); - int originalPostId = rs.getInt("original_post_id"); - String originalPosterName = rs.getString("original_poster_name"); - String originalPosterAvatar = rs.getString("original_poster_avatar"); - int shareCount = rs.getInt("share_count"); + try (PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, userId); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + int post_id = rs.getInt("post_id"); + int user_id = rs.getInt("user_id"); + String body = rs.getString("body"); + Timestamp post_time = rs.getTimestamp("post_time"); + String first_name = rs.getString("first_name"); + String last_name = rs.getString("last_name"); + int like_count = rs.getInt("like_count"); + String image_path = rs.getString("image_path"); + String profile_pic = rs.getString("profile_pic"); + boolean isShared = rs.getBoolean("is_shared"); + int originalPostId = rs.getInt("original_post_id"); + String originalPosterName = rs.getString("original_poster_name"); + String originalPosterAvatar = rs.getString("original_poster_avatar"); + int shareCount = rs.getInt("share_count"); - Post post = new Post(post_id, user_id, body, post_time, first_name, last_name, image_path, profile_pic, like_count, isShared, originalPostId, originalPosterName, shareCount, originalPosterAvatar); - posts.add(post); + Post post = new Post(post_id, user_id, body, post_time, first_name, last_name, image_path, profile_pic, like_count, isShared, originalPostId, originalPosterName, shareCount, originalPosterAvatar); + String type = rs.getString("type"); + post.setType(type); + posts.add(post); + + } } } - } - } catch (SQLException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - return posts; -} - - public void deletePost(int postId) { - String deletePostQuery = "DELETE FROM post WHERE post_id = ?"; - - try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(deletePostQuery)) { - stmt.setInt(1, postId); - stmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } - + return posts; } public void sharePost(int userId, int postId) throws SQLException { @@ -327,8 +345,271 @@ public void sharePost(int userId, int postId) throws SQLException { } } - public static void main(String[] args) { - List posts; - posts = getMyPosts(2); + public void updatePost(Post p) { + String updatePostQuery = "UPDATE post SET body = ? WHERE post_id = ?"; + String updateSharedPostsQuery = "UPDATE post SET body = ? WHERE original_post_id = ? AND is_shared = 1"; + String updateImageQuery = "UPDATE post SET image_path = ?,type=? WHERE post_id = ?"; + String updateSharedImageQuery = "UPDATE post SET image_path = ?,type= ? WHERE original_post_id = ? AND is_shared = 1"; + + try (Connection conn = sqlConnect.getInstance().getConnection()) { + conn.setAutoCommit(false); + try { + try (PreparedStatement stmt = conn.prepareStatement(updatePostQuery)) { + stmt.setString(1, p.getBody()); + stmt.setInt(2, p.getPost_id()); + stmt.executeUpdate(); + } + try (PreparedStatement stmt = conn.prepareStatement(updateSharedPostsQuery)) { + stmt.setString(1, p.getBody()); + stmt.setInt(2, p.getPost_id()); + stmt.executeUpdate(); + } + if (p.getImage_path() != null && !p.getImage_path().isEmpty()) { + try (PreparedStatement stmt = conn.prepareStatement(updateImageQuery)) { + stmt.setString(1, p.getImage_path()); + stmt.setString(2, p.getType()); + stmt.setInt(3, p.getPost_id()); + stmt.executeUpdate(); + } + try (PreparedStatement stmt = conn.prepareStatement(updateSharedImageQuery)) { + stmt.setString(1, p.getImage_path()); + stmt.setString(2, p.getType()); + stmt.setInt(3, p.getPost_id()); + stmt.executeUpdate(); + } + } + + conn.commit(); + } catch (SQLException e) { + conn.rollback(); + throw e; + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void updateComment(Comment c) { + String updateCommentQuery = "UPDATE comment SET comment_text = ? WHERE comment_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection()) { + conn.setAutoCommit(false); + try (PreparedStatement stmt = conn.prepareStatement(updateCommentQuery)) { + stmt.setString(1, c.getComment_text()); + stmt.setInt(2, c.getComment_id()); + stmt.executeUpdate(); + conn.commit(); + } catch (SQLException ex) { + conn.rollback(); + Logger.getLogger(postDAO.class.getName()).log(Level.SEVERE, null, ex); + throw ex; + } + } catch (SQLException ex) { + Logger.getLogger(postDAO.class.getName()).log(Level.SEVERE, null, ex); + } catch (Exception ex) { + Logger.getLogger(postDAO.class.getName()).log(Level.SEVERE, null, ex); + } } + + public void deletePost(int postId) { + String deletePostQuery = "DELETE FROM post WHERE post_id = ? OR (original_post_id = ? AND is_shared = 1)"; + String deleteCommentsQuery = "DELETE FROM comment WHERE post_id = ? OR post_id IN (SELECT post_id FROM post WHERE original_post_id = ? AND is_shared = 1)"; + String deleteLikesQuery = "DELETE FROM post_like WHERE post_id = ? OR post_id IN (SELECT post_id FROM post WHERE original_post_id = ? AND is_shared = 1)"; + String deleteSharesQuery = "DELETE FROM post_share WHERE post_id = ? OR post_id IN (SELECT post_id FROM post WHERE original_post_id = ? AND is_shared = 1)"; + + try (Connection conn = sqlConnect.getInstance().getConnection()) { + conn.setAutoCommit(false); + try { + try (PreparedStatement stmt = conn.prepareStatement(deleteCommentsQuery)) { + stmt.setInt(1, postId); + stmt.setInt(2, postId); + stmt.executeUpdate(); + } + try (PreparedStatement stmt = conn.prepareStatement(deleteLikesQuery)) { + stmt.setInt(1, postId); + stmt.setInt(2, postId); + stmt.executeUpdate(); + } + try (PreparedStatement stmt = conn.prepareStatement(deleteSharesQuery)) { + stmt.setInt(1, postId); + stmt.setInt(2, postId); + stmt.executeUpdate(); + } + try (PreparedStatement stmt = conn.prepareStatement(deletePostQuery)) { + stmt.setInt(1, postId); + stmt.setInt(2, postId); + stmt.executeUpdate(); + } + conn.commit(); + } catch (SQLException e) { + conn.rollback(); + throw e; + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void deleteComment(int commentId) { + String deleteCommentQuery = "DELETE FROM comment WHERE comment_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection()) { + conn.setAutoCommit(false); + try (PreparedStatement stmt = conn.prepareStatement(deleteCommentQuery)) { + stmt.setInt(1, commentId); + stmt.executeUpdate(); + conn.commit(); + } catch (SQLException e) { + conn.rollback(); + throw e; + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception ex) { + Logger.getLogger(postDAO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void savePost(int userId, int postId) throws SQLException { + String query = "INSERT INTO saved_post (user_id, post_id) VALUES (?, ?)"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, userId); + stmt.setInt(2, postId); + stmt.executeUpdate(); + } catch (Exception ex) { + Logger.getLogger(postDAO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void unsavePost(int userId, int postId) throws SQLException { + String query = "DELETE FROM saved_post WHERE user_id = ? AND post_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, userId); + stmt.setInt(2, postId); + stmt.executeUpdate(); + } catch (Exception ex) { + Logger.getLogger(postDAO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public boolean isPostSavedByUser(int userId, int postId) { + String query = "SELECT COUNT(*) FROM saved_post WHERE user_id = ? AND post_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, userId); + stmt.setInt(2, postId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return rs.getInt(1) > 0; + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return false; + } + + public List getSavedPosts(int userId) { + List posts = new ArrayList<>(); + String query = "SELECT p.post_id, p.body, p.post_time, p.user_id, p.image_path, p.like_count, p.type, u.first_name, u.last_name, u.profile_pic, " + + "p.is_shared, p.original_post_id, p.privacy_mode, " + + "CASE WHEN p.is_shared = 1 THEN CONCAT(op.first_name, ' ', op.last_name) ELSE NULL END AS original_poster_name, " + + "CASE WHEN p.is_shared = 1 THEN op.profile_pic ELSE NULL END AS original_poster_avatar, " + + "(SELECT COUNT(*) FROM post_share WHERE post_id = p.post_id) AS share_count " + + "FROM post p " + + "JOIN userAccount u ON p.user_id = u.user_id " + + "LEFT JOIN post op_post ON p.original_post_id = op_post.post_id " + + "LEFT JOIN userAccount op ON op_post.user_id = op.user_id " + + "JOIN saved_post sp ON p.post_id = sp.post_id " + + "WHERE sp.user_id = ? " + + "ORDER BY p.post_time DESC"; + + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, userId); + try (ResultSet rs = stmt.executeQuery()) { + while (rs.next()) { + int post_id = rs.getInt("post_id"); + int user_id = rs.getInt("user_id"); + String body = rs.getString("body"); + Timestamp post_time = rs.getTimestamp("post_time"); + String first_name = rs.getString("first_name"); + String last_name = rs.getString("last_name"); + String image_path = rs.getString("image_path"); + int like_count = rs.getInt("like_count"); + String profile_pic = rs.getString("profile_pic"); + boolean isShared = rs.getBoolean("is_shared"); + int originalPostId = rs.getInt("original_post_id"); + String originalPosterName = rs.getString("original_poster_name"); + int shareCount = rs.getInt("share_count"); + String originalPosterAvatar = rs.getString("original_poster_avatar"); + String privacy_mode = rs.getString("privacy_mode"); + + Post post = new Post(post_id, user_id, body, post_time, first_name, last_name, image_path, profile_pic, like_count, isShared, originalPostId, originalPosterName, shareCount, originalPosterAvatar, privacy_mode); + post.setComments(getComments(post.getPost_id())); + String type = rs.getString("type"); + post.setType(type); + posts.add(post); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return posts; + } + + public Post getPostById(int postId) { + Post post = null; + try { + Connection conn = sqlConnect.getInstance().getConnection(); + String query = "SELECT p.post_id, p.body, p.post_time, p.user_id, p.like_count, p.image_path, " + + "u.first_name, u.last_name, u.profile_pic, " + + "p.is_shared, p.original_post_id, " + + "CASE WHEN p.is_shared = 1 THEN CONCAT(op.first_name, ' ', op.last_name) ELSE NULL END AS original_poster_name, " + + "CASE WHEN p.is_shared = 1 THEN op.profile_pic ELSE NULL END AS original_poster_avatar, " + + "(SELECT COUNT(*) FROM post_share WHERE post_id = p.post_id) AS share_count " + + "FROM post p " + + "JOIN userAccount u ON p.user_id = u.user_id " + + "LEFT JOIN post op_post ON p.original_post_id = op_post.post_id " + + "LEFT JOIN userAccount op ON op_post.user_id = op.user_id " + + "WHERE p.post_id = ?"; + + try (PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, postId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + int post_id = rs.getInt("post_id"); + int user_id = rs.getInt("user_id"); + String body = rs.getString("body"); + Timestamp post_time = rs.getTimestamp("post_time"); + String first_name = rs.getString("first_name"); + String last_name = rs.getString("last_name"); + int like_count = rs.getInt("like_count"); + String image_path = rs.getString("image_path"); + String profile_pic = rs.getString("profile_pic"); + boolean isShared = rs.getBoolean("is_shared"); + int originalPostId = rs.getInt("original_post_id"); + String originalPosterName = rs.getString("original_poster_name"); + String originalPosterAvatar = rs.getString("original_poster_avatar"); + int shareCount = rs.getInt("share_count"); + + post = new Post(post_id, user_id, body, post_time, first_name, last_name, image_path, profile_pic, like_count, isShared, originalPostId, originalPosterName, shareCount, originalPosterAvatar); + String type = rs.getString("type"); + post.setType(type); + } + } + } + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception e) { + e.printStackTrace(); + } + return post; + } + + + + } diff --git a/src/java/dao/shoppingCartDAO.java b/src/java/dao/shoppingCartDAO.java index b7f90da..b605a93 100644 --- a/src/java/dao/shoppingCartDAO.java +++ b/src/java/dao/shoppingCartDAO.java @@ -18,22 +18,23 @@ * @author ADMIN */ public class shoppingCartDAO { + private Connection connection; - - public List getAllCarts() throws Exception{ + + public List getAllCarts() throws Exception { List shoppingList = new ArrayList<>(); // ket noi sql va lay thong tin list shopping cart tu database String sql = "SELECT * FROM shoppingCart"; - + try { connection = sqlConnect.getInstance().getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); - while(resultSet.next()){ + while (resultSet.next()) { int cart_id = resultSet.getInt("cart_id"); int user_id = resultSet.getInt("user_id"); Date add_date = resultSet.getDate("add_date"); - + ShoppingCart shoppingCart = new ShoppingCart(cart_id, user_id, add_date); shoppingList.add(shoppingCart); } @@ -71,27 +72,27 @@ public List getAllItems(int cart_id) throws Exception { } // Tạo giỏ hàng - public void addShoppingCart(int userId) throws SQLException, Exception { - String sql = "INSERT INTO shoppingCart (user_id, add_date) VALUES (?, GETDATE())"; - connection = sqlConnect.getInstance().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(sql); - preparedStatement.setInt(1, userId); - preparedStatement.executeUpdate(); -} - +// public void addShoppingCart(int userId) throws SQLException, Exception { +// String sql = "INSERT INTO shoppingCart (user_id, add_date) VALUES (?, GETDATE())"; +// connection = sqlConnect.getInstance().getConnection(); +// PreparedStatement preparedStatement = connection.prepareStatement(sql); +// preparedStatement.setInt(1, userId); +// preparedStatement.executeUpdate(); +// } + // Thêm item vào shopping cart public boolean addShoppingCartItem(int cartId, int productId, int quantity) throws SQLException, Exception { - String sql = "INSERT INTO shoppingCartItem (cart_id, product_id, quantity) VALUES (?, ?, ?)"; - connection = sqlConnect.getInstance().getConnection(); - PreparedStatement preparedStatement = connection.prepareStatement(sql); - preparedStatement.setInt(1, cartId); - preparedStatement.setInt(2, productId); - preparedStatement.setInt(3, quantity); - - int rowsAffected = preparedStatement.executeUpdate(); - return rowsAffected > 0; // Trả về true nếu có ít nhất 1 dòng bị ảnh hưởng + String sql = "INSERT INTO shoppingCartItem (cart_id, product_id, quantity) VALUES (?, ?, ?)"; + connection = sqlConnect.getInstance().getConnection(); + PreparedStatement preparedStatement = connection.prepareStatement(sql); + preparedStatement.setInt(1, cartId); + preparedStatement.setInt(2, productId); + preparedStatement.setInt(3, quantity); + + int rowsAffected = preparedStatement.executeUpdate(); + return rowsAffected > 0; // Trả về true nếu có ít nhất 1 dòng bị ảnh hưởng } - + public int getCartIdByUserId(int userId) throws Exception { String sql = "SELECT cart_id FROM shoppingCart WHERE user_id = ?"; connection = sqlConnect.getInstance().getConnection(); @@ -124,18 +125,17 @@ public int getUserIdByCartId(int cartId) throws Exception { return userId; } - + // Phương thức xóa sản phẩm khỏi giỏ hàng public void removeItem(int cartId, int productId) throws SQLException, Exception { String sql = "DELETE FROM shoppingCartItem WHERE cart_id = ? AND product_id = ?"; - try (Connection conn = sqlConnect.getInstance().getConnection(); - PreparedStatement stmt = conn.prepareStatement(sql)) { + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, cartId); stmt.setInt(2, productId); stmt.executeUpdate(); } } - + public static void main(String[] args) throws Exception { shoppingCartDAO s = new shoppingCartDAO(); System.out.println(s.getUserIdByCartId(4)); diff --git a/src/java/dao/userDAO.java b/src/java/dao/userDAO.java index 202cd4e..4d9ab6a 100644 --- a/src/java/dao/userDAO.java +++ b/src/java/dao/userDAO.java @@ -1,18 +1,18 @@ package dao; -import Security.SHA512WithSalt; import util.sqlConnect; import java.sql.*; import model.User; import java.util.ArrayList; -import java.util.Base64; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; public class userDAO { private static userDAO instance = null; - private userDAO() { + public userDAO() { } @@ -27,60 +27,20 @@ public boolean login(String email, String password) { boolean result = false; try { Connection conn = sqlConnect.getInstance().getConnection(); - PreparedStatement st = conn.prepareStatement("SELECT * FROM userAccount WHERE email=?"); + PreparedStatement st = conn.prepareStatement("Select * from userAccount where email=? AND password=?"); st.setString(1, email); + st.setString(2, password); ResultSet rs = st.executeQuery(); - if (rs.next()) { - // Lấy chuỗi kết hợp (lưu cả salt và sha512 hash vào password) - String combinedHash = rs.getString("password"); - - // Tách salt và hashedPassword - String[] parts = combinedHash.split(":"); // Sử dụng dấu phân cách - byte[] salt = Base64.getDecoder().decode(parts[0]); // Giải mã salt - String storedHash = parts[1]; // hashedPassword - - // Băm mật khẩu đã nhập với salt - String hashedInputPassword = SHA512WithSalt.hashPassWordWithSHA512(password, salt); - - // So sánh mật khẩu đã băm - if (hashedInputPassword.equals(storedHash)) { - result = true; - } + result = true; } } catch (Exception e) { - System.out.println("Connect Failed: " + e.getMessage()); + System.out.println("Connect Failed"); } return result; } - - public void hashPw(String firstName, String lastName, String email, String password, String profilePic, String role) throws Exception { - userDAO uDAO = new userDAO(); // Giả định UserDAO có phương thức register - - // Bước 1: Mã hóa mật khẩu với salt - byte[] salt = SHA512WithSalt.createSalt(); // Tạo salt - String hashedPassword = SHA512WithSalt.hashPassWordWithSHA512(password, salt); // Băm mật khẩu với SHA-512 - String combinedHash = Base64.getEncoder().encodeToString(salt) + ":" + hashedPassword; // Kết hợp salt và mật khẩu đã băm - - // Bước 2: Tạo đối tượng User mới - User newUser = new User(firstName, lastName, combinedHash, email, profilePic, role, false); // false ở đây là is_banned - - // Bước 3: Gọi phương thức register để thêm người dùng vào cơ sở dữ liệu - int userId = uDAO.register(newUser); // Phương thức register trả về userId nếu thành công - - // Bước 4: Kiểm tra kết quả đăng ký - if (userId > 0) { - System.out.println("Đăng ký thành công cho email: " + email + " với userId: " + userId); - } else { - System.out.println("Đăng ký thất bại cho email: " + email); - } - } public int register(User user) throws Exception { - // tạo giỏ hàng cho người dùng khi register - shoppingCartDAO sCartDAO = new shoppingCartDAO(); - sCartDAO.addShoppingCart(user.getUser_id()); - int generatedUserId = 0; String sql = "INSERT INTO userAccount (first_name, last_name, password, email, profile_pic, role, is_banned) " + "VALUES (?, ?, ?, ?, ?, ?, ?)"; @@ -94,7 +54,7 @@ public int register(User user) throws Exception { ps.setBoolean(7, user.getStatus()); ps.executeUpdate(); - + ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { generatedUserId = rs.getInt(1); // Get the generated user_id @@ -102,9 +62,7 @@ public int register(User user) throws Exception { } catch (SQLException e) { e.printStackTrace(); } - return generatedUserId; - } public User getUserByEmail(String email) { @@ -174,6 +132,7 @@ public static ArrayList getAllUserByName(String name, int current_userId) u.setUser_id(rs.getInt(1)); u.setFirst_name(rs.getString(2)); u.setLast_name(rs.getString(3)); + u.setRole(rs.getString("role")); u.setProfile_pic(rs.getString(4)); userList.add(u); } @@ -228,6 +187,7 @@ public ArrayList getAllUsers() throws Exception { u.setFirst_name(rs.getString("first_name")); u.setLast_name(rs.getString("last_name")); u.setEmail(rs.getString("email")); + u.setRole(rs.getString("role")); u.setProfile_pic(rs.getString("profile_pic")); users.add(u); } @@ -292,8 +252,8 @@ public void changePassword(String password, String email) { } } - public List findFriendsByKeyWord(int userId, String keyWord) throws SQLException, Exception { - String sql = "SELECT u.user_id, u.profile_pic, u.first_name, u.last_name" + public ArrayList findFriendsByKeyWord(int userId, String keyWord) throws SQLException, Exception { + String sql = "SELECT u.user_id, u.profile_pic, u.first_name, u.last_name " + "FROM userAccount u " + "WHERE u.user_id != ? AND (u.first_name LIKE ? OR u.last_name LIKE ?)"; @@ -304,13 +264,13 @@ public List findFriendsByKeyWord(int userId, String keyWord) throws SQLExc ps.setString(3, "%" + keyWord + "%"); ResultSet rs = ps.executeQuery(); - List users = new ArrayList<>(); + ArrayList users = new ArrayList<>(); while (rs.next()) { User user = new User(); user.setUser_id(rs.getInt("user_id")); user.setProfile_pic(rs.getString("profile_pic")); - user.setFirst_name("first_name"); - user.setLast_name("last_name"); + user.setFirst_name(rs.getString("first_name")); + user.setLast_name(rs.getString("last_name")); users.add(user); } return users; @@ -320,7 +280,7 @@ public List findFriendsByKeyWord(int userId, String keyWord) throws SQLExc public List findUsersByConversationId(int conversationId) throws SQLException, Exception { String sql = "SELECT u.user_id, u.profile_pic, u.last_name, u.first_name, cu.is_admin " + "FROM userAccount u " - + "JOIN conversations_users cu ON u.user_id = cu.user_id " + + "JOIN conversation_users cu ON u.user_id = cu.user_id " + "WHERE cu.conversation_id = ?"; try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { @@ -333,8 +293,8 @@ public List findUsersByConversationId(int conversationId) throws SQLExcept User user = new User(); user.setUser_id(rs.getInt("user_id")); user.setProfile_pic(rs.getString("profile_pic")); - user.setFirst_name("first_name"); - user.setLast_name("last_name"); + user.setFirst_name(rs.getString("first_name")); + user.setLast_name(rs.getString("last_name")); user.setAdmin(rs.getBoolean("is_admin")); users.add(user); } @@ -342,39 +302,72 @@ public List findUsersByConversationId(int conversationId) throws SQLExcept } } - public List findFriendsNotInConversation(int userId, String keyword, int conversationId) throws SQLException, Exception { - String sql = "SELECT u2.user_id, u2.profile_pic, u2.last_name, u2.first_name" + public List getFriendsNotInConversation(int userId, String keyword, int conversationId) throws SQLException, Exception { + List list = new ArrayList<>(); + String sql = "SELECT DISTINCT u2.user_id, u2.profile_pic, u2.last_name, u2.first_name " + "FROM userAccount u1 " - + "JOIN friendship f ON u1.user_id = f.receiver " - + "JOIN userAccount u2 ON u2.user_id = f.sender " - + "WHERE u1.user_id = ? AND f.status = 1 AND (u2.first_name LIKE ? OR u2.last_name LIKE ?) " + + "LEFT JOIN friendship f ON (u1.user_id = f.receiver OR u1.user_id = f.sender) " + + "LEFT JOIN userAccount u2 ON (u2.user_id = f.sender OR u2.user_id = f.receiver) " + + "WHERE u1.user_id != u2.user_id " + + "AND u1.user_id = ? " + + "AND f.status = 'accepted' " + + "AND (u2.first_name LIKE ? OR u2.last_name LIKE ?) " + "AND u2.user_id NOT IN ( " + " SELECT u.user_id FROM userAccount u " - + " JOIN conversations_users cu ON u.user_id = cu.user_id " + + " JOIN conversation_users cu ON u.user_id = cu.user_id " + " WHERE cu.conversation_id = ? )"; try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement ps = conn.prepareStatement(sql)) { - ps.setInt(1, userId); ps.setString(2, "%" + keyword + "%"); ps.setString(3, "%" + keyword + "%"); ps.setInt(4, conversationId); ResultSet rs = ps.executeQuery(); - List users = new ArrayList<>(); while (rs.next()) { User user = new User(); user.setUser_id(rs.getInt("user_id")); user.setProfile_pic(rs.getString("profile_pic")); - user.setFirst_name("first_name"); - user.setLast_name("last_name"); - users.add(user); + user.setLast_name(rs.getString("last_name")); + user.setFirst_name(rs.getString("first_name")); + list.add(user); } - return users; + } + return list; + } + + public void updateUserIntroduction(int userId, String introduction) { + String query = "UPDATE userAccount SET user_introduce = ? WHERE user_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setString(1, introduction); + stmt.setInt(2, userId); + stmt.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } catch (Exception ex) { + ex.printStackTrace(); } } - - public static void main(String[] args) { - userDAO.getInstance().login("nguyenhuuanhtuan123@gmail.com", "123"); + + public String getUserIntroduce(int sessionUserId) { + String query = "SELECT user_introduce FROM userAccount WHERE user_id = ?"; + try (Connection conn = sqlConnect.getInstance().getConnection(); PreparedStatement stmt = conn.prepareStatement(query)) { + stmt.setInt(1, sessionUserId); + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + return rs.getString("user_introduce"); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return "Xin chao`"; + } + + public static void main(String[] args) throws Exception { + List list = userDAO.getInstance().findUsersByConversationId(1); + for (User user : list) { + System.out.println(user.getFirst_name()); + } } } diff --git a/src/java/dtos/UserDTO.java b/src/java/dtos/UserDTO.java index f69281a..d6c05ea 100644 --- a/src/java/dtos/UserDTO.java +++ b/src/java/dtos/UserDTO.java @@ -25,7 +25,7 @@ public UserDTO() { public UserDTO(@JsonProperty("user_id") int userId, @JsonProperty("first_name") String firstName, @JsonProperty("last_name") String lastName, - @JsonProperty("profile)_pic") String profile_pic, + @JsonProperty("profile_pic") String profile_pic, @JsonProperty("isAdmin") boolean isAdmin) { this.userId = userId; this.firstName = firstName; diff --git a/src/java/model/Comment.java b/src/java/model/Comment.java index b3c6734..e9b3fdf 100644 --- a/src/java/model/Comment.java +++ b/src/java/model/Comment.java @@ -9,6 +9,7 @@ * @author bim26 */ public class Comment { + private int comment_id; private int post_id; private int user_id; @@ -16,8 +17,9 @@ public class Comment { private String last_name; private String comment_text; private String profile_pic; + private String comment_image; - public Comment(int comment_id, int post_id, int user_id, String first_name, String last_name, String comment_text, String profile_pic) { + public Comment(int comment_id, int post_id, int user_id, String first_name, String last_name, String comment_text, String profile_pic, String comment_image) { this.comment_id = comment_id; this.post_id = post_id; this.user_id = user_id; @@ -25,9 +27,20 @@ public Comment(int comment_id, int post_id, int user_id, String first_name, Stri this.last_name = last_name; this.comment_text = comment_text; this.profile_pic = profile_pic; + this.comment_image = comment_image; } + + public Comment(int comment_id, int post_id, int user_id, String first_name, String last_name, String comment_text, String profile_pic) { + this.comment_id = comment_id; + this.post_id = post_id; + this.user_id = user_id; + this.first_name = first_name; + this.last_name = last_name; + this.comment_text = comment_text; + this.profile_pic = profile_pic; + } public Comment(int comment_id, int post_id, int user_id, String first_name, String last_name, String comment_text) { this.comment_id = comment_id; @@ -41,6 +54,16 @@ public Comment(int comment_id, int post_id, int user_id, String first_name, Stri public Comment() { } + public String getComment_image() { + return comment_image; + } + + public void setComment_image(String comment_image) { + this.comment_image = comment_image; + } + + + public String getProfile_pic() { return profile_pic; } @@ -48,7 +71,7 @@ public String getProfile_pic() { public void setProfile_pic(String profile_pic) { this.profile_pic = profile_pic; } - + public int getComment_id() { return comment_id; } @@ -96,6 +119,5 @@ public String getComment_text() { public void setComment_text(String comment_text) { this.comment_text = comment_text; } - - + } diff --git a/src/java/model/Conversation.java b/src/java/model/Conversation.java index 6f5d307..8277e82 100644 --- a/src/java/model/Conversation.java +++ b/src/java/model/Conversation.java @@ -15,8 +15,6 @@ public class Conversation { private int id; private String name; private String avatar; - private List users; - public Conversation() { } diff --git a/src/java/model/LearningMaterial.java b/src/java/model/LearningMaterial.java index 7c584b1..2d78740 100644 --- a/src/java/model/LearningMaterial.java +++ b/src/java/model/LearningMaterial.java @@ -1,5 +1,15 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ package model; +/** + * + * @author gabri + */ + + import java.util.Date; public class LearningMaterial { @@ -10,32 +20,37 @@ public class LearningMaterial { private int userId; private String learningMaterialName; private String learningMaterialDescription; - private String learningMaterial_img; private String learningMaterialContext; private String subjectCode; private Date publishDate; private String review; + private int departmentId; - public LearningMaterial(int learningMaterialId, int userId, String learningMaterialName, String learningMaterialDescription, String learningMaterial_img, String learningMaterialContext, String subjectCode, Date publishDate, String review) { + public LearningMaterial(int learningMaterialId, int userId, String learningMaterialName, String learningMaterialDescription, String learningMaterialContext, String subjectCode, Date publishDate, String review, int departmentId) { this.learningMaterialId = learningMaterialId; this.userId = userId; this.learningMaterialName = learningMaterialName; this.learningMaterialDescription = learningMaterialDescription; - this.learningMaterial_img = learningMaterial_img; this.learningMaterialContext = learningMaterialContext; this.subjectCode = subjectCode; this.publishDate = publishDate; this.review = review; + this.departmentId = departmentId; } - public String getLearningMaterial_img() { - return learningMaterial_img; + + + // Getters and setters for all fields, including departmentId + public int getDepartmentId() { + return departmentId; } - public void setLearningMaterial_img(String learningMaterial_img) { - this.learningMaterial_img = learningMaterial_img; + public void setDepartmentId(int departmentId) { + this.departmentId = departmentId; } + + public int getLearningMaterialId() { return learningMaterialId; } @@ -100,3 +115,4 @@ public void setReview(String review) { this.review = review; } } + diff --git a/src/java/model/Month.java b/src/java/model/Month.java new file mode 100644 index 0000000..cd8582b --- /dev/null +++ b/src/java/model/Month.java @@ -0,0 +1,44 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package model; + +/** + * + * @author Quocb + */ +public class Month { + private String Name; + private Integer Count; + + public Month(String Name, Integer Count) { + this.Name = Name; + this.Count = Count; + } + + public Month() { + } + + public String getName() { + return Name; + } + + public void setName(String Name) { + this.Name = Name; + } + + public Integer getCount() { + return Count; + } + + public void setCount(Integer Count) { + this.Count = Count; + } + + @Override + public String toString() { + return "Month{" + "Name=" + Name + ", Count=" + Count + '}'; + } + +} diff --git a/src/java/model/OrderDetailDTO.java b/src/java/model/OrderDetailDTO.java new file mode 100644 index 0000000..3a14d7c --- /dev/null +++ b/src/java/model/OrderDetailDTO.java @@ -0,0 +1,90 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package model; + +import java.util.Date; + +/** + * + * @author ADMIN + */ +public class OrderDetailDTO { + private int orderId; + private String productName; + private int quantity; + private double price; + private String orderStatus; + private Date orderDate; + private String sellerName; + + public OrderDetailDTO(int orderId, String productName, int quantity, double price, + String orderStatus, Date orderDate, String sellerName) { + this.orderId = orderId; + this.productName = productName; + this.quantity = quantity; + this.price = price; + this.orderStatus = orderStatus; + this.orderDate = orderDate; + this.sellerName = sellerName; + } + + public int getOrderId() { + return orderId; + } + + public void setOrderId(int orderId) { + this.orderId = orderId; + } + + public String getProductName() { + return productName; + } + + public void setProductName(String productName) { + this.productName = productName; + } + + public int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public String getOrderStatus() { + return orderStatus; + } + + public void setOrderStatus(String orderStatus) { + this.orderStatus = orderStatus; + } + + public Date getOrderDate() { + return orderDate; + } + + public void setOrderDate(Date orderDate) { + this.orderDate = orderDate; + } + + public String getSellerName() { + return sellerName; + } + + public void setSellerName(String sellerName) { + this.sellerName = sellerName; + } + + +} \ No newline at end of file diff --git a/src/java/model/Orders.java b/src/java/model/Orders.java index 05c039d..938a85f 100644 --- a/src/java/model/Orders.java +++ b/src/java/model/Orders.java @@ -105,6 +105,4 @@ public void setShipping_address(String shipping_address) { public String toString() { return "Orders{" + "order_id=" + order_id + ", user_id=" + user_id + ", cart_id=" + cart_id + ", total_amount=" + total_amount + ", order_status=" + order_status + ", order_date=" + order_date + ", order_note=" + order_note + ", shipping_address=" + shipping_address + '}'; } - - -} +} \ No newline at end of file diff --git a/src/java/model/Post.java b/src/java/model/Post.java index 30cca9a..0fed4d5 100644 --- a/src/java/model/Post.java +++ b/src/java/model/Post.java @@ -28,6 +28,27 @@ public class Post { private String originalPosterName; private int shareCount; private String originalPosterAvatar; + private String privacy_mode; + private boolean savedByCurrentUser; + private String type; + + public Post(int post_id, int user_id, String body, Timestamp post_time, String first_name, String last_name, String image_path, String profile_pic, int like_count, boolean isShared, int originalPostId, String originalPosterName, int shareCount, String originalPosterAvatar, String privacy_mode) { + this.post_id = post_id; + this.user_id = user_id; + this.body = body; + this.post_time = post_time; + this.first_name = first_name; + this.last_name = last_name; + this.image_path = image_path; + this.profile_pic = profile_pic; + this.like_count = like_count; + this.isShared = isShared; + this.originalPostId = originalPostId; + this.originalPosterName = originalPosterName; + this.shareCount = shareCount; + this.originalPosterAvatar = originalPosterAvatar; + this.privacy_mode = privacy_mode; + } public Post(int post_id, int user_id, String body, Timestamp post_time, String first_name, String last_name, String image_path, String profile_pic, int like_count, boolean isShared, int originalPostId, String originalPosterName, int shareCount, String originalPosterAvatar) { this.post_id = post_id; @@ -47,6 +68,7 @@ public Post(int post_id, int user_id, String body, Timestamp post_time, String f } + public Post(int post_id, int user_id, String body, Timestamp post_time, String first_name, String last_name, String image_path, String profile_pic, int like_count, boolean likedByCurrentUser, List comments) { this.post_id = post_id; @@ -76,6 +98,24 @@ public Post(int post_id, int user_id, String body, Timestamp post_time, String f this.comments = comments; } + public boolean isSavedByCurrentUser() { + return savedByCurrentUser; + } + + public void setSavedByCurrentUser(boolean savedByCurrentUser) { + this.savedByCurrentUser = savedByCurrentUser; + } + + public String getPrivacy_mode() { + return privacy_mode; + } + + public void setPrivacy_mode(String privacy_mode) { + this.privacy_mode = privacy_mode; + } + + + public List getComments() { return comments; } @@ -201,6 +241,15 @@ public Post(int post_id, int user_id, String body, Timestamp post_time, String f this.profile_pic = profile_pic; this.like_count = like_count; } + + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } public String getProfile_pic() { @@ -253,6 +302,7 @@ public Post(int post_id, int user_id, String body, Timestamp post_time) { } + public Post() { } @@ -294,7 +344,12 @@ public void setPost_time(Timestamp post_time) { this.post_time = post_time; } + @Override + public String toString() { + return "Post{" + "post_id=" + post_id + ", user_id=" + user_id + ", body=" + body + ", post_time=" + post_time + ", first_name=" + first_name + ", last_name=" + last_name + ", image_path=" + image_path + ", profile_pic=" + profile_pic + ", like_count=" + like_count + ", likedByCurrentUser=" + likedByCurrentUser + ", comments=" + comments + ", isShared=" + isShared + ", originalPostId=" + originalPostId + ", originalPosterName=" + originalPosterName + ", shareCount=" + shareCount + ", originalPosterAvatar=" + originalPosterAvatar + ", type=" + type + '}'; + } + } - \ No newline at end of file + diff --git a/src/java/model/User.java b/src/java/model/User.java index 387a8b9..b1b3685 100644 --- a/src/java/model/User.java +++ b/src/java/model/User.java @@ -19,11 +19,30 @@ public class User { private String role; private boolean is_banned; private boolean isAdmin; - + private String user_introduce; public User() { } + public User(int user_id, String first_name, String last_name, String password, String email, String profile_pic, String role, boolean is_banned, boolean isAdmin, String user_introduce) { + this.user_id = user_id; + this.first_name = first_name; + this.last_name = last_name; + this.password = password; + this.email = email; + this.profile_pic = profile_pic; + this.role = role; + this.is_banned = is_banned; + this.isAdmin = isAdmin; + this.user_introduce = user_introduce; + } + + public User(String user_introduce) { + this.user_introduce = user_introduce; + } + + + public User(int user_id, String first_name, String last_name, String profile_pic) { this.user_id = user_id; this.first_name = first_name; @@ -55,6 +74,12 @@ public User(int user_id, String first_name, String last_name, String password, S this.isAdmin = isAdmin; } + public User(int user_id, String user_introduce) { + this.user_id = user_id; + this.user_introduce = user_introduce; + } + + public int getUser_id() { return user_id; } @@ -134,5 +159,13 @@ public boolean isAdmin() { public void setAdmin(boolean isAdmin) { this.isAdmin = isAdmin; } + + public String getUser_introduce() { + return user_introduce; + } + + public void setUser_introduce(String user_introduce) { + this.user_introduce = user_introduce; + } } diff --git a/src/java/model/UserActivityLog.java b/src/java/model/UserActivityLog.java new file mode 100644 index 0000000..cffcf2c --- /dev/null +++ b/src/java/model/UserActivityLog.java @@ -0,0 +1,140 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package model; + +/** + * + * @author Quocb + */ +import java.time.LocalDateTime; +import java.util.Date; + +public class UserActivityLog { + private int logId; + private int userId; + private String role; + private String activityType; + private String FirstName; + private String LastName; + private int postId; + private int commentId; + private String activityDetails; + private LocalDateTime timestamp; + + public UserActivityLog(int logId, int userId, String role, String activityType, String FirstName, String LastName, String activityDetails, LocalDateTime timestamp) { + this.logId = logId; + this.userId = userId; + this.role = role; + this.activityType = activityType; + this.FirstName = FirstName; + this.LastName = LastName; + this.activityDetails = activityDetails; + this.timestamp = timestamp; + } + + + + public UserActivityLog(int logId, int userId, String activityType, String activityDetails, LocalDateTime timestamp) { + this.logId = logId; + this.userId = userId; + this.activityType = activityType; + this.activityDetails = activityDetails; + this.timestamp = timestamp; + } + + public int getPostId() { + return postId; + } + + public void setPostId(int postId) { + this.postId = postId; + } + + public int getCommentId() { + return commentId; + } + + public void setCommentId(int commentId) { + this.commentId = commentId; + } + + + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + public String getFirstName() { + return FirstName; + } + + public void setFirstName(String FirstName) { + this.FirstName = FirstName; + } + + public String getLastName() { + return LastName; + } + + public void setLastName(String LastName) { + this.LastName = LastName; + } + + + + public UserActivityLog() { + } + + + public int getLogId() { + return logId; + } + + public void setLogId(int logId) { + this.logId = logId; + } + + public int getUserId() { + return userId; + } + + public void setUserId(int userId) { + this.userId = userId; + } + + public String getActivityType() { + return activityType; + } + + public void setActivityType(String activityType) { + this.activityType = activityType; + } + + public String getActivityDetails() { + return activityDetails; + } + + public void setActivityDetails(String activityDetails) { + this.activityDetails = activityDetails; + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } + + @Override + public String toString() { + return "UserActivityLog{" + "logId=" + logId + ", userId=" + userId + ", role=" + role + ", activityType=" + activityType + ", FirstName=" + FirstName + ", LastName=" + LastName + ", postId=" + postId + ", commentId=" + commentId + ", activityDetails=" + activityDetails + ", timestamp=" + timestamp + '}'; + } + + + +} diff --git a/src/java/model/game.java b/src/java/model/game.java new file mode 100644 index 0000000..53b014d --- /dev/null +++ b/src/java/model/game.java @@ -0,0 +1,74 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template + */ +package model; + +/** + * + * @author Quocb + */ +public class game { + private int Magame; + private String tengame; + private String link; + private String linkimg; + private String theloai; + + public game(int Magame, String tengame, String link, String linkimg, String theloai) { + this.Magame = Magame; + this.tengame = tengame; + this.link = link; + this.linkimg = linkimg; + this.theloai = theloai; + } + + public String getLinkimg() { + return linkimg; + } + + public void setLinkimg(String linkimg) { + this.linkimg = linkimg; + } + + + + public int getMagame() { + return Magame; + } + + public void setMagame(int Magame) { + this.Magame = Magame; + } + + public String getTengame() { + return tengame; + } + + public void setTengame(String tengame) { + this.tengame = tengame; + } + + public String getLink() { + return link; + } + + public void setLink(String link) { + this.link = link; + } + + public String getTheloai() { + return theloai; + } + + public void setTheloai(String theloai) { + this.theloai = theloai; + } + + @Override + public String toString() { + return "game{" + "Magame=" + Magame + ", tengame=" + tengame + ", link=" + link + ", linkimg=" + linkimg + ", theloai=" + theloai + '}'; + } + + +} diff --git a/src/java/services/ChatService.java b/src/java/services/ChatService.java index 8d991ed..4220fe9 100644 --- a/src/java/services/ChatService.java +++ b/src/java/services/ChatService.java @@ -1,9 +1,10 @@ package services; +import com.cloudinary.utils.ObjectUtils; import dao.userDAO; +import dtos.FileDTO; import jakarta.websocket.EncodeException; import java.io.IOException; -import java.util.Set; import java.util.HashSet; import java.util.List; import java.util.concurrent.CopyOnWriteArraySet; @@ -11,9 +12,17 @@ import websockets.ChatWebsocket; import model.User; import dtos.MessageDTO; +import java.io.File; +import java.nio.ByteBuffer; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.logging.Logger; +import util.CloudinaryAPI; public class ChatService { + private static final Logger LOGGER = Logger.getLogger(ChatService.class.getName()); private userDAO userDao = userDAO.getInstance(); private static ChatService chatService = null; protected static final Set chatWebsockets = new CopyOnWriteArraySet<>(); @@ -56,40 +65,45 @@ public void sendMessageToAllUsers(MessageDTO message) { }); } - public void sendMessageToOneUser(MessageDTO message) throws Exception { - if (message.getReceiver() != 0) { - // Send message to a single user - chatWebsockets.stream() - .filter(chatWebsocket -> chatWebsocket.getUserId() == message.getReceiver()) - .forEach(chatWebsocket -> { - try { - chatWebsocket.getSession().getBasicRemote().sendObject(message); - } catch (IOException | EncodeException e) { - e.printStackTrace(); - } - }); - } else { - // Send message to a group of users - List usersGroup = userDao.findUsersByConversationId(message.getGroupId()); - - // Collect all user IDs in the group - List userIdGroup = usersGroup.stream() - .map(User::getUser_id) - .collect(Collectors.toList()); - - // Send the message to all users in the group, excluding the sender - chatWebsockets.stream() - .filter(chatWebsocket -> userIdGroup.contains(chatWebsocket.getUserId()) - && chatWebsocket.getUserId() != message.getSender()) // Filter out the sender - .forEach(chatWebsocket -> { - try { - chatWebsocket.getSession().getBasicRemote().sendObject(message); - } catch (IOException | EncodeException e) { - System.err.println("Error sending message to user: " + chatWebsocket.getUserId()); - e.printStackTrace(); - } - }); + public void sendMessageToOneUser(MessageDTO message, Queue fileDTOs) throws Exception { + // Send message to a single user + if (!message.getType().equals("text")) { + String url = message.getMessage(); + String typeFile = message.getType(); + if (typeFile.startsWith("audio")) { + message.setMessage(""); + } else if (typeFile.startsWith("video")) { + message.setMessage(""); + } else if (typeFile.startsWith("image")) { + message.setMessage("\"\""); + } } + chatWebsockets.stream() + .filter(chatWebsocket -> chatWebsocket.getUserId() == message.getReceiver()) + .forEach(chatWebsocket -> { + try { + chatWebsocket.getSession().getBasicRemote().sendObject(message); + } catch (IOException | EncodeException e) { + e.printStackTrace(); + } + }); + } + + public void sendMessageToGroup(MessageDTO message, Queue fileDTOs) throws Exception { + List usersGroup = userDao.findUsersByConversationId(message.getGroupId()); + Set userIdGroup = usersGroup.stream().map(User::getUser_id).collect(Collectors.toSet()); + chatWebsockets.stream() + .filter(chatWebsocket -> userIdGroup.contains(chatWebsocket.getUserId()) + && chatWebsocket.getUserId() != message.getSender()) + .forEach(chatWebsocket -> { + try { + chatWebsocket.getSession().getBasicRemote().sendObject(message); + } catch (IOException | EncodeException e) { + e.printStackTrace(); + } + }); } protected Set getIdList() { diff --git a/src/java/services/ConversationService.java b/src/java/services/ConversationService.java index 67adfe8..b1ff360 100644 --- a/src/java/services/ConversationService.java +++ b/src/java/services/ConversationService.java @@ -20,6 +20,7 @@ import dtos.ConversationDTO; import dtos.MessageDTO; import dtos.UserDTO; +import java.util.ArrayList; /** * @@ -27,148 +28,161 @@ */ public class ConversationService { - private ConversationDAO conversationDAO = ConversationDAO.getInstance(); - - private userDAO userDaoInterface = userDAO.getInstance(); - - private MessageDao messageDaoInterface = MessageDao.getInstance(); - - private static ConversationService instance = null; - - private ConversationService() { - - } - - public synchronized static ConversationService getInstance() { - if (instance == null) { - instance = new ConversationService(); - } - return instance; - } - - private User convertToUserEntity(UserDTO userDTO) { - User user = new User(); - user.setUser_id(userDTO.getUserId()); - user.setAdmin(userDTO.isIsAdmin()); - return user; - } - - private UserDTO convertToUserDTO(User user) { - UserDTO userDTO = new UserDTO(); - user.setUser_id(userDTO.getUserId()); - userDTO.setProfile_pic(user.getProfile_pic()); - user.setAdmin(userDTO.isIsAdmin()); - return userDTO; - } - - private ConversationDTO convertToConversationDTO(Conversation conversation) { - ConversationDTO conversationDTO = new ConversationDTO(); - conversationDTO.setId(conversation.getId()); - conversationDTO.setName(conversation.getName()); - conversationDTO.setAvatar(conversation.getAvatar().trim()); - return conversationDTO; - } - - private Conversation convertToConversation(ConversationDTO conversationDTO) { - Conversation conversation = new Conversation(); - conversation.setId(conversationDTO.getId()); - conversation.setName(conversationDTO.getName()); - if (conversationDTO.getAvatar() != null && !conversationDTO.getAvatar().isEmpty()) { - conversation.setAvatar(conversationDTO.getAvatar().trim()); - } - return conversation; - } - - private MessageDTO convertToMessageDTO(Message messageEntity) { - int user_id = messageEntity.getSender(); - String type = messageEntity.getType(); - String message = messageEntity.getMessage(); - if (!type.equals("text")) { - message = FileService.toTagHtml(type, user_id, message); - } - int receiver = messageEntity.getReceiver(); - int groupId = messageEntity.getGroupId(); - MessageDTO messageDTO = new MessageDTO(user_id, receiver, message, type, groupId); - return messageDTO; - } - - public void saveConversation(ConversationDTO conversationDTO) throws Exception { - Conversation conversation = convertToConversation(conversationDTO); - List users = conversationDTO.getUsers().stream().map(userDTO -> convertToUserEntity(userDTO)) - .collect(Collectors.toList()); - conversationDAO.saveConversation(conversation, users); - conversationDTO.setId(conversation.getId()); - - String dirName = "group-" + conversationDTO.getId(); - File privateDir = new File(FileService.rootLocation.toString() + "/" + dirName); - privateDir.mkdir(); - String fileName = dirName + ".png"; - File newFile = new File(privateDir.toString() + "/" + fileName); - try { - File defaultAvatar = new File(FileService.rootLocation.toString() + "/default/group.png"); - Files.copy(defaultAvatar.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - conversation.setAvatar(fileName); - conversationDAO.saveConversation(conversation, null); - conversationDTO.setAvatar(fileName); - } catch (IOException ex) { - } - } - - public List getAllConversationsById(int user_id) throws Exception { - List conversations = conversationDAO.findAllConversationsByUserId(user_id); - List conversationDTOs = conversations.stream() - .map(conversation -> convertToConversationDTO(conversation)).collect(Collectors.toList()); - return conversationDTOs; - } - - public List getAllUsersByConversationId(int id) throws Exception { - List userDTOs = userDaoInterface.findUsersByConversationId(id).stream() - .map(user -> convertToUserDTO(user)).collect(Collectors.toList()); - return userDTOs; - } - - public List getAllMessagesByConversationId(int id) throws Exception { - List messageDTOs = messageDaoInterface.findAllMessagesByConversationId(id).stream() - .map(message -> convertToMessageDTO(message)).collect(Collectors.toList()); - return messageDTOs; - } - - public void updateConversationById(int id, String name, Part avatar) throws Exception { - try { - String fileName = ""; - String origin = avatar.getSubmittedFileName(); - if (!origin.isEmpty()) { - String dirName = "group-" + id; - File privateDir = new File(FileService.rootLocation.toString() + "/" + dirName); - String tail = origin.substring(origin.lastIndexOf("."), origin.length()); - fileName = dirName + tail; - System.err.println("file: " + fileName); - avatar.write(privateDir.getAbsolutePath() + File.separator + fileName); - } - Conversation conversation = new Conversation(id, name, fileName); - conversationDAO.saveConversation(conversation, null); - } catch (IOException ex) { - } - } - - public ConversationDTO getConversationById(int id) throws Exception { - Conversation conversation = conversationDAO.findConversationById(id); - return convertToConversationDTO(conversation); - } - - public void deleteConversationById(int id) throws Exception { - conversationDAO.deleteConversationById(id); - - } - - public void deleteUserFromConversation(int conversationId, int user_id) throws Exception { - conversationDAO.deleteUserFromConversation(conversationId, user_id); - } - - public List getConversationsOfUserByKeyword(int user_id, String keyword) throws Exception { - List conversationDTOs = conversationDAO - .findConversationsOfUserByKeyword(user_id, keyword).stream() - .map(conversation -> convertToConversationDTO(conversation)).collect(Collectors.toList()); - return conversationDTOs; - } -} \ No newline at end of file + private ConversationDAO conversationDAO = ConversationDAO.getInstance(); + + private userDAO userDaoInterface = userDAO.getInstance(); + + private MessageDao messageDaoInterface = MessageDao.getInstance(); + + private static ConversationService instance = null; + + private ConversationService() { + + } + + public synchronized static ConversationService getInstance() { + if (instance == null) { + instance = new ConversationService(); + } + return instance; + } + + private User convertToUserEntity(UserDTO userDTO) { + User user = new User(); + user.setUser_id(userDTO.getUserId()); + user.setAdmin(userDTO.isIsAdmin()); + return user; + } + + //Sau này thêm set first last name để hiển thị trong group + private UserDTO convertToUserDTO(User user) { + UserDTO userDTO = new UserDTO(); + userDTO.setFirstName(user.getFirst_name()); + userDTO.setLastName(user.getLast_name()); + userDTO.setUserId(user.getUser_id()); + userDTO.setProfile_pic(user.getProfile_pic()); + userDTO.setIsAdmin(user.isAdmin()); + return userDTO; + } + + private ConversationDTO convertToConversationDTO(Conversation conversation) { + ConversationDTO conversationDTO = new ConversationDTO(); + conversationDTO.setId(conversation.getId()); + conversationDTO.setName(conversation.getName()); + conversationDTO.setAvatar(conversation.getAvatar().trim()); + return conversationDTO; + } + + private Conversation convertToConversation(ConversationDTO conversationDTO) { + Conversation conversation = new Conversation(); + conversation.setId(conversationDTO.getId()); + conversation.setName(conversationDTO.getName()); + if (conversationDTO.getAvatar() != null && !conversationDTO.getAvatar().isEmpty()) { + conversation.setAvatar(conversationDTO.getAvatar().trim()); + } + return conversation; + } + + private MessageDTO convertToMessageDTO(Message messageEntity) { + int user_id = messageEntity.getSender(); + String type = messageEntity.getType(); + String message = messageEntity.getMessage(); + if (!type.equals("text")) { + message = FileService.toTagHtml(type, user_id, message); + } + int receiver = messageEntity.getReceiver(); + int groupId = messageEntity.getGroupId(); + MessageDTO messageDTO = new MessageDTO(user_id, receiver, message, type, groupId); + return messageDTO; + } + + public void saveConversation(ConversationDTO conversationDTO) throws Exception { + Conversation conversation = convertToConversation(conversationDTO); + List users = conversationDTO.getUsers().stream().map(userDTO -> convertToUserEntity(userDTO)) + .collect(Collectors.toList()); + conversationDAO.saveConversation(conversation, users); + conversationDTO.setId(conversation.getId()); + +// String dirName = "group-" + conversationDTO.getId(); +// File privateDir = new File(FileService.rootLocation.toString() + "/" + dirName); +// privateDir.mkdir(); +// String fileName = dirName + ".png"; +// File newFile = new File(privateDir.toString() + "/" + fileName); +// try { +// File defaultAvatar = new File(FileService.rootLocation.toString() + "/default/group.png"); +// Files.copy(defaultAvatar.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); +// conversation.setAvatar(fileName); +// conversationDAO.saveConversation(conversation, null); +// conversationDTO.setAvatar(fileName); +// } catch (IOException ex) { +// } + } + + public List getAllConversationsById(int user_id) throws Exception { + List conversations = conversationDAO.findAllConversationsByUserId(user_id); + List conversationDTOs = conversations.stream() + .map(conversation -> convertToConversationDTO(conversation)).collect(Collectors.toList()); + return conversationDTOs; + } + + public List getAllUsersByConversationId(int id) throws Exception { + List userDTOs = userDaoInterface.findUsersByConversationId(id).stream() + .map(user -> convertToUserDTO(user)).collect(Collectors.toList()); + return userDTOs; + } + + public List getAllMessagesByConversationId(int id) throws Exception { + List messageDTOs = messageDaoInterface.findAllMessagesByConversationId(id).stream() + .map(message -> convertToMessageDTO(message)).collect(Collectors.toList()); + return messageDTOs; + } + + public void updateConversationById(int id, String name, String avatar) throws Exception { + try { + Conversation conversation = new Conversation(id, name, avatar); + conversationDAO.updateConversation(conversation); + } catch (IOException ex) { + } + } + + public ConversationDTO getConversationById(int id) throws Exception { + Conversation conversation = conversationDAO.findConversationById(id); + return convertToConversationDTO(conversation); + } + + public void deleteConversationById(int id) throws Exception { + conversationDAO.deleteConversationById(id); + + } + + public void deleteUserFromConversation(int conversationId, int user_id) throws Exception { + conversationDAO.deleteUserFromConversation(conversationId, user_id); + } + + public List getConversationsOfUserByKeyword(int user_id, String keyword) throws Exception { + List conversationDTOs = conversationDAO + .findConversationsOfUserByKeyword(user_id, keyword).stream() + .map(conversation -> convertToConversationDTO(conversation)).collect(Collectors.toList()); + return conversationDTOs; + } + + public static void main(String[] args) throws Exception { +// UserDTO user = new UserDTO(); +// user.setIsAdmin(true); +// user.setUserId(2); +// List list = new ArrayList<>(); +// list.add(user); +// ConversationDTO conversationDTO = new ConversationDTO(0, "abc", "abc", list); +// ConversationService.getInstance().saveConversation(conversationDTO); + +// List c = ConversationService.getInstance().getAllConversationsById(2); +// for (ConversationDTO ca : c) { +// System.out.println(ca.getId()); +// } +// List user = ConversationService.getInstance().getAllUsersByConversationId(4); +// System.out.println(user.size()); +// System.out.println(user.get(0).getUserId()); + List message = ConversationService.getInstance().getAllUsersByConversationId(1); + System.out.println(message.get(0).getFirstName()); + } +} diff --git a/src/java/services/FileService.java b/src/java/services/FileService.java index 73c656c..9998fd4 100644 --- a/src/java/services/FileService.java +++ b/src/java/services/FileService.java @@ -34,19 +34,18 @@ public static FileService getInstance() { // Generate HTML tag based on file type public static String toTagHtml(String type, int user_id, String message) { String tag = ""; - String url = rootURL + user_id + "/" + message; if (type.startsWith("audio")) { tag = ""; } else if (type.startsWith("video")) { tag = ""; } else if (type.startsWith("image")) { - tag = "\"\""; + tag = "\"\""; } else { - tag = "" + message + ""; + tag = "" + message + ""; } return tag; } diff --git a/src/java/services/MessageService.java b/src/java/services/MessageService.java index bbfcbd2..6fbd683 100644 --- a/src/java/services/MessageService.java +++ b/src/java/services/MessageService.java @@ -4,13 +4,24 @@ */ package services; +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; +import controller.postServlet; import dao.MessageDao; import java.util.ArrayList; import java.util.List; import model.Message; import dtos.MessageDTO; +import jakarta.servlet.ServletException; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; +import util.CloudinaryAPI; /** * @@ -20,60 +31,61 @@ public class MessageService { private static MessageService instance = null; - private MessageDao messageDAO = MessageDao.getInstance(); + private MessageDao messageDAO = MessageDao.getInstance(); - public static MessageService getInstance() { - if (instance == null) { - instance = new MessageService(); - } - return instance; - } - - private Message convertToEntity(MessageDTO messageDTO) { - int user_id = messageDTO.getSender(); - String message = messageDTO.getMessage(); - String type = messageDTO.getType(); - int receiver = messageDTO.getReceiver(); - int groupId = messageDTO.getGroupId(); - Message messageEntity = new Message(user_id, receiver, message, type, groupId); - return messageEntity; - } + private Cloudinary cloud; - private MessageDTO convertToDTO(Message messageEntity) { - int user_id = messageEntity.getSender(); - String type = messageEntity.getType(); - String message = messageEntity.getMessage(); - if (!type.equals("text")) { - message = FileService.toTagHtml(type, user_id, message); - } - int receiver = messageEntity.getReceiver(); - int groupId = messageEntity.getGroupId(); - MessageDTO messageDTO = new MessageDTO(user_id, receiver, message, type, groupId); - return messageDTO; - } + public static MessageService getInstance() { + if (instance == null) { + instance = new MessageService(); + } + return instance; + } + + private Message convertToEntity(MessageDTO messageDTO) { + int user_id = messageDTO.getSender(); + String message = messageDTO.getMessage(); + String type = messageDTO.getType(); + int receiver = messageDTO.getReceiver(); + int groupId = messageDTO.getGroupId(); + Message messageEntity = new Message(user_id, receiver, message, type, groupId); + return messageEntity; + } + + private MessageDTO convertToDTO(Message messageEntity) { + int user_id = messageEntity.getSender(); + String type = messageEntity.getType(); + String message = messageEntity.getMessage(); + if (!type.equals("text")) { + message = FileService.toTagHtml(type, user_id, message); + } + int receiver = messageEntity.getReceiver(); + int groupId = messageEntity.getGroupId(); + MessageDTO messageDTO = new MessageDTO(user_id, receiver, message, type, groupId); + return messageDTO; + } - public List getAllMessagesBySenderAndReceiver(int sender, int receiver) throws Exception { - List listMessages = messageDAO.findAllMessagesBySenderAndReceiver(sender, receiver); - List listMessageDTOs = new ArrayList<>(); - listMessages.stream().forEach(msg -> { - MessageDTO messageDTO = convertToDTO(msg); - listMessageDTOs.add(messageDTO); - }); - return listMessageDTOs; - } + public List getAllMessagesBySenderAndReceiver(int sender, int receiver) throws Exception { + List listMessages = messageDAO.findAllMessagesBySenderAndReceiver(sender, receiver); + List listMessageDTOs = new ArrayList<>(); + listMessages.stream().forEach(msg -> { + MessageDTO messageDTO = convertToDTO(msg); + listMessageDTOs.add(messageDTO); + }); + return listMessageDTOs; + } - public void saveMessage(MessageDTO messageDTO) { + public void saveMessage(MessageDTO messageDTO) { try { Message messageEntity = convertToEntity(messageDTO); messageDAO.saveMessage(messageEntity); } catch (Exception ex) { System.out.println("Err here"); } - } - - public static void main(String[] args) { - MessageDTO msg = new MessageDTO(1, 2, "ok", "text", 0); - MessageService service = new MessageService(); - service.saveMessage(msg); + } + + public static void main(String[] args) throws Exception { + List list = MessageService.getInstance().getAllMessagesBySenderAndReceiver(1, 2); + System.out.println(list.get(list.size()-1).getMessage()); } } diff --git a/src/java/util/CloudinaryAPI.java b/src/java/util/CloudinaryAPI.java new file mode 100644 index 0000000..e4e6358 --- /dev/null +++ b/src/java/util/CloudinaryAPI.java @@ -0,0 +1,43 @@ +/* + * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license + * Click nbfs://nbhost/SystemFileSystem/Templates/Other/File.java to edit this template + */ +package util; + +import com.cloudinary.Cloudinary; +import com.cloudinary.utils.ObjectUtils; + +/** + * + * @author HELLO + */ +public class CloudinaryAPI { + + private static Cloudinary cloud; + private static final Object lock = new Object(); // To ensure thread-safety + + private CloudinaryAPI() { + // Private constructor to prevent instantiation + } + + public static Cloudinary getInstance() { + if (cloud == null) { + synchronized (lock) { + if (cloud == null) { + // Load Cloudinary config from properties file + String cloudName = "dxx8u5qnr"; + String apiKey = "694793228885481"; + String apiSecret = "ydUuGLOQjJ2UTdMaiJes0zggIpw"; + + cloud = new Cloudinary(ObjectUtils.asMap( + "cloud_name", cloudName, + "api_key", apiKey, + "api_secret", apiSecret + )); + + } + } + } + return cloud; + } +} diff --git a/src/java/util/sqlConnect.java b/src/java/util/sqlConnect.java index bc18a23..9b4713d 100644 --- a/src/java/util/sqlConnect.java +++ b/src/java/util/sqlConnect.java @@ -22,9 +22,9 @@ public class sqlConnect { private String port = "1433"; private String ip = "127.0.0.1"; private String dbName = "FUNET"; - private String deviceName = "MSI"; + private String deviceName = "WINDOWS-10"; private String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; - private String sqlUrl = "jdbc:sqlserver://MSI;databaseName=FUNET;encrypt=false;trustServerCertificate=false"; + private String sqlUrl = "jdbc:sqlserver://" + deviceName + ";databaseName=FUNET;encrypt=false;trustServerCertificate=false"; private sqlConnect() throws Exception { try { @@ -47,4 +47,4 @@ public static sqlConnect getInstance() throws SQLException, Exception { public Connection getConnection() { return connection; } -} +} \ No newline at end of file diff --git a/src/java/websockets/ChatWebsocket.java b/src/java/websockets/ChatWebsocket.java index 041074d..ca447b9 100644 --- a/src/java/websockets/ChatWebsocket.java +++ b/src/java/websockets/ChatWebsocket.java @@ -1,23 +1,32 @@ package websockets; -import dao.MessageDao; +import com.cloudinary.utils.ObjectUtils; +import dtos.FileDTO; import jakarta.websocket.OnClose; import jakarta.websocket.OnMessage; import jakarta.websocket.OnOpen; import jakarta.websocket.Session; import jakarta.websocket.server.PathParam; import jakarta.websocket.server.ServerEndpoint; -import model.Message; import services.ChatService; import jakarta.websocket.DecodeException; import dtos.MessageDTO; +import java.io.File; +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.Map; +import java.util.Queue; import services.MessageService; +import java.util.logging.Logger; +import util.CloudinaryAPI; @ServerEndpoint(value = "/chat/{user_id}", encoders = MessageEncoder.class, decoders = MessageDecoder.class) public class ChatWebsocket { + private static final Logger LOGGER = Logger.getLogger(ChatWebsocket.class.getName()); private Session session; private int user_id; + private Queue fileDTOs = new LinkedList<>(); ChatService chatService = ChatService.getInstance(); MessageService messageService = MessageService.getInstance(); @@ -33,7 +42,12 @@ public void onOpen(@PathParam("user_id") int user_id, Session session) { @OnMessage public void onMessage(MessageDTO message, Session session) throws DecodeException, Exception { - chatService.sendMessageToOneUser(message); + if (message.getReceiver() != 0) { + chatService.sendMessageToOneUser(message, fileDTOs); + } else { + message.setReceiver(0); + chatService.sendMessageToGroup(message, fileDTOs); + } messageService.saveMessage(message); } diff --git a/web/WEB-INF/DashBoard.jsp b/web/WEB-INF/DashBoard.jsp new file mode 100644 index 0000000..af9c9a4 --- /dev/null +++ b/web/WEB-INF/DashBoard.jsp @@ -0,0 +1,184 @@ +<%-- + Document : DashBoard + Created on : 5 thg 10, 2024, 23:15:47 + Author : Quocb +--%> + +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> +<%@ page import="java.util.List, model.Post, dao.postDAO, model.User" %> +<%@ page import="model.UserActivityLog" %> +<%@ taglib prefix="c" uri="jakarta.tags.core"%> +<%@ taglib prefix="fmt" uri="jakarta.tags.fmt"%> + + + + + + Admin Dashboard + + + + + +
+
+ + + + +
+ +
+

Dashboard

+
+
+
+
+
Total Users
+

10,234

+
+
+
+
+
+
+
New Posts Today
+

156

+
+
+
+
+
+
+
Active Users
+

8,742

+
+
+
+
+
+ + +
+

Users Management

+ + + + + + + + + + + + + + + + + + + + + + +
User IdRoleName
${user.user_id}${user.role} ${user.first_name} ${user.last_name}
+
+ + +
+

Analytics

+
+
+ +
+
+ +
+
+
+
+
+
+ + + + + + diff --git a/web/WEB-INF/LearningMaterial.jsp b/web/WEB-INF/LearningMaterial.jsp new file mode 100644 index 0000000..3ba2585 --- /dev/null +++ b/web/WEB-INF/LearningMaterial.jsp @@ -0,0 +1,347 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> +<%@ page import="java.util.List, model.Post, dao.postDAO, model.User" %> +<%@ page import="model.Message, dao.MessageDao" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> +<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> + + + + + + Home Page + + + + + + + + + + + + + + + + + + + + + +
+ + + + + +
+ +
+
+ +
+
+ + +
+
+ +
+
+ + +
${material.learningMaterialName}
+

${material.learningMaterialDescription}

+

Subject: ${material.subjectCode}

+

Published on: ${material.publishDate}

+

Review: ${material.review}

+ Download this document +
+
+
+
+
+ +
+

Create Learning Material

+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+
+ + +
+
+ + + + + + + + \ No newline at end of file diff --git a/web/WEB-INF/addProduct.jsp b/web/WEB-INF/addProduct.jsp index 555c68d..e3375c9 100644 --- a/web/WEB-INF/addProduct.jsp +++ b/web/WEB-INF/addProduct.jsp @@ -80,40 +80,25 @@
@@ -154,4 +139,4 @@ - + \ No newline at end of file diff --git a/web/WEB-INF/chatbox.jsp b/web/WEB-INF/chatbox.jsp index 8c2eb91..3b56adb 100644 --- a/web/WEB-INF/chatbox.jsp +++ b/web/WEB-INF/chatbox.jsp @@ -12,10 +12,51 @@ + +
+ + + + + + + + + + + - - - - \ No newline at end of file + + + + + diff --git a/web/WEB-INF/log.jsp b/web/WEB-INF/log.jsp new file mode 100644 index 0000000..2405345 --- /dev/null +++ b/web/WEB-INF/log.jsp @@ -0,0 +1,50 @@ +<%@page contentType="text/html" pageEncoding="UTF-8"%> + + + + + User Log + + + + +
+

Users Management

+ + <% String userId = request.getParameter("id");%> + + + + + + + + + + + + + + + + + + + + + + + +
Post IdRoleNameActivity TypePost idComment idDetailsTimeDelete
+
+ + + + + + + diff --git a/web/WEB-INF/market.jsp b/web/WEB-INF/market.jsp index 5c2ff0a..5f39203 100644 --- a/web/WEB-INF/market.jsp +++ b/web/WEB-INF/market.jsp @@ -56,30 +56,20 @@