Skip to content

Commit

Permalink
Added a working MessageCenter JSP
Browse files Browse the repository at this point in the history
  • Loading branch information
panuozzo77 committed Dec 29, 2023
1 parent 58e0ff8 commit 4a67e9c
Show file tree
Hide file tree
Showing 8 changed files with 338 additions and 218 deletions.
11 changes: 11 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,17 @@
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>

<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
</dependencies>

<build>
Expand Down
27 changes: 5 additions & 22 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,15 @@
import model.DAO.DAOUser;
import model.entity.User;
import model.service.login.Authenticator;
//import model.service.message.Conversation;
import model.service.registration.Registration;

public class Main {
public static void main(String[] args) {
Encryption encryption = new Encryption();
DAOUser db = new DAOUser();
String plainTextPassword = "123456";
EmailManager message = new EmailManager();

/*
String hashedPassword = encryption.encryptPassword(plainTextPassword);
//Conversation conv = new Conversation(9);
//System.out.println(conv.getUnreadMessagesCounter());
//System.out.println(conv.getConversations());

// Use hashed password to create new user
db.createUser("[email protected]", hashedPassword, 0);
*/

/*
User user = db.getUserByIdOrEmail("[email protected]");
System.out.println(encryption.verifyPassword(plainTextPassword, user.getPassword()));
*/


//test email
//message.sendEmail("[email protected]", "Email Test", "questo è una email di test");

//test email recupero password
Authenticator authenticator = new Authenticator();
System.out.println(authenticator.authenticate("[email protected]", "123456"));
}
}
72 changes: 72 additions & 0 deletions src/main/java/controller/GetMessageServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package controller;

import java.io.IOException;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.entity.Message;
import model.service.message.Conversation;
import java.util.List;
import javax.json.*;

@WebServlet("/GetMessages")
public class GetMessageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int userId = (int) session.getAttribute("id");

int contactId = Integer.parseInt(request.getParameter("contact_id")); // Get the contact's ID from the request

// Retrieve the messages between the user and the contact
Conversation conversation = new Conversation();
List<Message> messages = conversation.retrieveMessages(userId, contactId);

// Now build the JSON response
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();

for (Message message : messages) {
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("sender", message.getSender());
jsonObjectBuilder.add("recipient", message.getRecipient());
jsonObjectBuilder.add("body", message.getBody());
// Convert timestamp to format HH:MM
Timestamp timestamp = message.getSent();
java.util.Date date = new java.util.Date(timestamp.getTime());
java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("HH:mm");
String formattedDate = dateFormat.format(date);

jsonObjectBuilder.add("sent", formattedDate);
jsonArrayBuilder.add(jsonObjectBuilder.build());
}
conversation.markMessagesAsRead(contactId, userId);
JsonArray jsonArray = jsonArrayBuilder.build();

response.setContentType("application/json");
response.getWriter().write(jsonArray.toString());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
HttpSession session = request.getSession();
int sender = (int) session.getAttribute("id");
int recipient = Integer.parseInt(request.getParameter("recipient"));
String body = request.getParameter("body");

// send the message
Conversation conversation = new Conversation();
conversation.sendMessage(sender, recipient, body);

response.getWriter().write("Message successfully sent");

} catch (NumberFormatException e) {
// The request parameter could not be parsed as an integer
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
}
}
}
94 changes: 93 additions & 1 deletion src/main/java/model/DAO/DAOMessage.java
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public List<Integer> retrieveUserIdsByTherapist(int therapistId) {
return userIds;
}

public Collection<Message> retrieveMessages(int userId, int contact) {
public List<Message> retrieveMessages(int userId, int contact) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Expand Down Expand Up @@ -111,4 +111,96 @@ public Collection<Message> retrieveMessages(int userId, int contact) {

return messages;
}

public void markMessagesAsRead(int senderId, int recipientId) {
Connection conn = null;
PreparedStatement pstmt = null;

try {
conn = DAOConnection.getConnection();

String sql = "UPDATE message SET `Read` = TRUE WHERE Sender = ? AND Recipient = ?;";

pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, senderId);
pstmt.setInt(2, recipientId);

pstmt.executeUpdate();

} catch (SQLException e) {
// Handle exceptions (e.g., print stack trace, log error, etc.)
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
DAOConnection.releaseConnection(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public void sendMessage(int sender, int recipient, String text) {
Connection conn = null;
PreparedStatement pstmt = null;

try {
conn = DAOConnection.getConnection();

String sql = "INSERT INTO message (Sender, Recipient, Body) VALUES (?, ?, ?);";

pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, sender);
pstmt.setInt(2, recipient);
pstmt.setString(3, text);

pstmt.executeUpdate();

} catch (SQLException e) {
// Handle exceptions (e.g., print stack trace, log error, etc.)
e.printStackTrace();
} finally {
try {
if (pstmt != null) pstmt.close();
DAOConnection.releaseConnection(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public int countReceivedMessages(int recipientId) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int count = 0;

try {
conn = DAOConnection.getConnection();

String sql = "SELECT COUNT(*) FROM message WHERE Recipient = ?;";

pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, recipientId);

rs = pstmt.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}

} catch (SQLException e) {
// Handle exceptions (e.g., print stack trace, log error, etc.)
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
DAOConnection.releaseConnection(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}

return count;
}
}
40 changes: 21 additions & 19 deletions src/main/java/model/service/message/Conversation.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,32 +29,34 @@ public Map<Integer, List<Message>> getConversations() {
return conversations;
}

public Conversation(int userId){
this.userId = userId;
List<Integer> contacts= retrieveAllTheContacts(userId);
forEachContactRetrieveTheMessages(userId, contacts);
updateUnreadCounter();
public Conversation(){}

public void markMessagesAsRead(int senderId, int recipientId) {
db.markMessagesAsRead(senderId, recipientId);
}

private void updateUnreadCounter() {
unreadMessages = 0;
for (List<Message> messages : conversations.values()) {
for (Message message : messages) {
if (message.getRecipient() == userId && !message.isRead()) {
unreadMessages++;
}
}
}
public int countReceivedMessages(int recipientId) {
return db.countReceivedMessages(recipientId);
}

private void forEachContactRetrieveTheMessages(int userId, List<Integer> contacts) {
for (int contact : contacts) {
conversations.put(contact, new ArrayList<>());
conversations.get(contact).addAll(db.retrieveMessages(userId, contact));
public void sendMessage(int sender, int recipientId, String text) {
db.sendMessage(sender, recipientId, text);
}
public List<Message> retrieveMessages(int userId, int contact) {
return db.retrieveMessages(userId, contact);
}
public int getUnreadMessagesForConversation(int userId, int contact){
int unreadCounter = 0;
List<Message> messages = db.retrieveMessages(userId, contact);
for (Message message : messages) {
if (message.getRecipient() == userId && !message.isRead()) {
unreadCounter++;
}
}
return unreadCounter;
}

private List<Integer> retrieveAllTheContacts(int userId){
public List<Integer> retrieveAllTheContacts(int userId){
List<Integer> contacts = new ArrayList<>();
UserData check = new UserData();
User user = check.getUserByIdOrEmail(userId);
Expand Down
98 changes: 98 additions & 0 deletions src/main/webapp/JS/message.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,102 @@ $(".newMessage-back").click(function() {
$(".side-two").css({
"left": "-100%"
});
});

var contact_id;
$(document).ready(function() {
$('.chat-box').on('click', function() {
// Remove "active" class from all ".chat-box" divs
$('.chat-box').removeClass('active');
// Add "active" class to the clicked ".chat-box"
$(this).addClass('active');

var contact_name = $(this).find(".text-head h4").text();
$('#contactOpened').text(contact_name);

var unread_indicator = $(this).find('.unread-messages');
unread_indicator.hide();

$(".right-container").removeAttr("hidden");
//access which type of ID the user wanted to read or message to
contact_id = $(this).data('contact-id');

if (contact_id === 0) {
// Prevent user from writing in the text field
$(".chatbox-input input").prop('readonly', true).attr('placeholder', "Non puoi inviare un messaggio");
} else {
// Allow user to write in the text field
$(".chatbox-input input").prop('readonly', false).attr('placeholder', "Componi un messaggio");
}
$.ajax({
url: '../GetMessages',
method: 'GET',
data: { contact_id: contact_id },
success: function(data) {
var chatContainer = $(".chat-container");
chatContainer.empty(); // Clear existing messages if any

data.forEach(function(message) {
// Determine if current user is sender or recipient
var messageBoxClass = contact_id == message.sender ? 'friend-message' : 'my-message'; // Replace userId with actual user id

var messageBox = $('<div>').addClass('message-box').addClass(messageBoxClass);
var messageContent = $('<p>').text(message.body);
var messageTime = $('<span>').text(message.sent);
messageContent.append($('<br>'), messageTime);
messageBox.append(messageContent);

chatContainer.append(messageBox);
});
},
error: function(error) {
// handle error response
}
});

});
});

$(document).ready(function() {
var input = $('.chatbox-input input');

input.on('keydown', function (e) {
if (e.key == 'Enter') {
e.preventDefault();

var message = input.val().trim(); // get the message from the input field

if (message === "") {
return; // if no message was typed and 'Enter' is pressed, do nothing
}
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();

// Pad with '0' to make sure we always get 2 digits
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;

var time = hours + ":" + minutes; // current time in "HH:MM" format
// append the message to the chat container
var msgHtml = '<div class="message-box my-message"><p>' + message + '<br><span>' + time + '</span></p></div>';
$('.chat-container').append(msgHtml);

// clear the input field
input.val('');

// make a POST request to your servlet
$.ajax({
url: '../GetMessages',
type: 'POST',
data: {
// change with actual sender ID
recipient: contact_id,
body: message
},
success: function (response) {
}
});
}
});
});
Loading

0 comments on commit 4a67e9c

Please sign in to comment.