Sending messages works! Kind of...

I give up on the database.
I'm switching to JSON.
This commit is contained in:
Norbi Peti 2016-07-29 11:56:03 +02:00
parent eb8eaa3834
commit 095269a585
8 changed files with 163 additions and 127 deletions

View file

@ -1,86 +1,86 @@
<!DOCTYPE html>
<head>
<title>ChatServer</title>
<script src="js/jquery-3.1.0.js"></script>
<script src="js/utils.js"></script>
<script src="js/message.js"></script>
<script src="js/login.js"></script>
<script src="js/register.js"></script>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div id="errormsg">
</div>
<div id="sidebar">
<div id="userbox">
Logged in as
<username/>
</div>
</div>
<div id="loginregisterbox">
<div id="loginbox">
<h2>Login</h2>
<form>
<table>
<tr>
<td>E-mail:</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="pass">
</td>
</tr>
<tr>
<td>
<input type="button" value="Login" onclick="login(this.form)">
</td>
</tr>
</table>
</form>
</div>
<div id="registerbox">
<h2>Register</h2>
<form>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td>
<input type="email" name="email"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="pass"/>
</td>
</tr>
<tr>
<td>Password confirm</td>
<td>
<input type="password" name="pass2"/>
</td>
</tr>
<tr>
<td>
<input type="button" value="Register" onclick="register(this.form)"/>
</td>
</tr>
</table>
</form>
</div>
</div>
<div id="usercontent">
<div id="channelmessages"></div>
<textarea id="msginput"></textarea>
</div>
</body>
<!DOCTYPE html>
<head>
<title>ChatServer</title>
<script src="js/jquery-3.1.0.js"></script>
<script src="js/utils.js"></script>
<script src="js/message.js"></script>
<script src="js/login.js"></script>
<script src="js/register.js"></script>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div id="errormsg">
</div>
<div id="sidebar">
<div id="userbox">
Logged in as
<username/>
</div>
</div>
<div id="loginregisterbox">
<div id="loginbox">
<h2>Login</h2>
<form>
<table>
<tr>
<td>E-mail:</td>
<td>
<input type="email" name="email">
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="pass">
</td>
</tr>
<tr>
<td>
<input type="button" value="Login" onclick="login(this.form)">
</td>
</tr>
</table>
</form>
</div>
<div id="registerbox">
<h2>Register</h2>
<form name="form">
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" name="name"/>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td>
<input type="email" name="email"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="pass"/>
</td>
</tr>
<tr>
<td>Password confirm</td>
<td>
<input type="password" name="pass2"/>
</td>
</tr>
<tr>
<td>
<input type="button" value="Register" onclick="register(this.form)"/>
</td>
</tr>
</table>
</form>
</div>
</div>
<div id="usercontent">
<div id="channelmessages"></div>
<textarea id="msginput"></textarea>
</div>
</body>

View file

@ -1,34 +1,28 @@
var respfunc = function (result) {
if (result.responseText != "Success") {
var respfunc = function respfunc(result) {
if (result != "Success") { //on success result is string
var errormsg = document.getElementById("errormsg");
errormsg.innerHTML = result.responseText;
errormsg.style = "display: block";
}
else
location.reload(true);
}
};
var sendmsgonenter = function (e) { //TODO: Detect Enter
console.log("A");
var sendmsgonenter = function sendmsgonenter(e) { //TODO: Detect Enter
var code = e.keyCode || e.which;
if (code != 13) { //Enter keycode
return;
}
console.log("B");
var textarea = event.target;
window.convid = 0;
window.convid = 1;
var json = JSON.stringify({"message": textarea.value, "conversation": window.convid});
$.ajax({
url: "/message", data: json, method: "POST", success: respfunc, error: respfunc
});
};
$(document).bind("ready", function () {
console.log("X");
$('#msginput').keypress = sendmsgonenter;
$(document).ready(function () {
$('#msginput').on("keypress", sendmsgonenter);
});
console.log(respfunc);
console.log(sendmsgonenter);
$('#msginput').bind("keypress", sendmsgonenter);
$('#msginput').on("keypress", sendmsgonenter);

View file

@ -51,7 +51,10 @@ public class Main {
System.out.println("2nd's contact: " + user2.getContacts().get(0));
Conversation convo = new Conversation();
convo.getUsers().add(user);
//user.getConversations().add(convo);
convo.getUsers().add(user2);
// user2.getConversations().add(convo); - TODO: Fix duplicate
// key constraint
Message msg = new Message();
msg.setSender(user);
msg.setTime(new Date());
@ -63,6 +66,16 @@ public class Main {
msg2.setMessage("Teszt 2");
convo.getMesssages().add(msg2);
provider.saveConversation(convo);
provider.saveUser(user);
provider.saveUser(user2);
User loggedinuser = new User();
loggedinuser.setName("NorbiPeti");
loggedinuser.setSessionid("2ed6e2cd-33ad-416e-92c2-7365510b8b31");
loggedinuser.setEmail("sznp@asd.com");
convo.getUsers().add(loggedinuser);
loggedinuser.getConversations().add(convo);
provider.saveUser(loggedinuser);
provider.saveConversation(convo);
}
System.out.println("Starting webserver...");
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 10);

View file

@ -1,7 +1,9 @@
package io.github.norbipeti.chat.server.db.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
@ -11,12 +13,13 @@ public class Conversation {
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@ElementCollection(fetch=FetchType.EAGER)
@OneToMany(cascade = CascadeType.ALL)
@ElementCollection(fetch = FetchType.EAGER)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "conversation")
private List<Message> messsages;
@ElementCollection(fetch = FetchType.EAGER)
@ManyToMany(cascade = CascadeType.ALL)
private List<User> users;
@JoinTable(name = "User_Conversation", joinColumns = @JoinColumn(name = "conversation_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"))
private Set<User> users;
public List<Message> getMesssages() {
if (messsages == null)
@ -28,13 +31,13 @@ public class Conversation {
this.messsages = messsages;
}
public List<User> getUsers() {
public Set<User> getUsers() {
if (users == null)
users = new ArrayList<>();
users = new HashSet<>();
return users;
}
public void setUsers(List<User> users) {
public void setUsers(Set<User> users) {
this.users = users;
}

View file

@ -15,7 +15,7 @@ public class Message {
private User sender;
private Date time;
private String message;
@ManyToOne(cascade=CascadeType.ALL)
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
//@JoinTable(name="conversation_message")
private Conversation conversation;

View file

@ -1,9 +1,10 @@
package io.github.norbipeti.chat.server.db.domain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Generated;
import javax.persistence.*;
@Entity
@ -19,12 +20,13 @@ public class User {
@ElementCollection(fetch = FetchType.EAGER)
private List<User> contacts;
private String salt;
//@Column(columnDefinition = "CHAR(16) FOR BIT DATA")
@Column(columnDefinition="VARCHAR(64)")
// @Column(columnDefinition = "CHAR(16) FOR BIT DATA")
@Column(columnDefinition = "VARCHAR(64)")
private String sessionid;
@ElementCollection(fetch = FetchType.EAGER)
@ManyToMany(cascade = CascadeType.ALL)
public List<Conversation> conversations;
// @ManyToMany(fetch = FetchType.EAGER, mappedBy = "users")
@ManyToMany(mappedBy = "users", fetch = FetchType.EAGER)
private Set<Conversation> conversations;
public List<User> getContacts() {
if (contacts == null)
@ -96,13 +98,13 @@ public class User {
this.sessionid = sessionid;
}
public List<Conversation> getConversations() {
public Set<Conversation> getConversations() {
if (conversations == null)
conversations = new ArrayList<>();
conversations = new HashSet<>();
return conversations;
}
public void setConversations(List<Conversation> conversations) {
public void setConversations(Set<Conversation> conversations) {
this.conversations = conversations;
}

View file

@ -16,10 +16,10 @@ public class IndexPage extends Page {
@Override
public void handlePage(HttpExchange exchange) throws IOException {
final User user = IOHelper.GetLoggedInUser(exchange);
/*final User user = new User();
user.setEmail("test@test.com");
user.setName("Norbi");
user.setId(3L);*/
/*
* final User user = new User(); user.setEmail("test@test.com");
* user.setName("Norbi"); user.setId(3L);
*/
if (user == null)
IOHelper.SendModifiedPage(200, this, (doc) -> {
doc.getElementById("userbox").remove();
@ -34,7 +34,9 @@ public class IndexPage extends Page {
userbox.html(userbox.html().replace("<username />", user.getName()));
Element channelmessages = doc.getElementById("channelmessages");
try (DataProvider provider = new DataProvider()) {
System.out.println("Conversations: " + provider.getConversations().size());
Conversation convo = provider.getConversations().get(0);
System.out.println("Messages: " + convo.getMesssages().size());
for (Message message : convo.getMesssages()) {
Element msgelement = channelmessages.appendElement("div");
Element header = msgelement.appendElement("p");

View file

@ -4,12 +4,14 @@ import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import io.github.norbipeti.chat.server.IOHelper;
import io.github.norbipeti.chat.server.db.DataProvider;
import io.github.norbipeti.chat.server.db.domain.Conversation;
import io.github.norbipeti.chat.server.db.domain.Message;
import io.github.norbipeti.chat.server.db.domain.User;
@ -26,7 +28,7 @@ public class MessageAjaxPage extends Page {
User user = IOHelper.GetLoggedInUser(exchange);
if (user == null) {
IOHelper.SendResponse(403, "<p>Please log in to send messages</p>", exchange);
return; //TODO: Fix sending messages
return; // TODO: Fix sending messages
}
JSONObject obj = IOHelper.GetPOSTJSON(exchange);
if (obj == null) {
@ -35,13 +37,33 @@ public class MessageAjaxPage extends Page {
}
String message = obj.getString("message");
int conversation = obj.getInt("conversation");
List<Conversation> convos = user.getConversations();
Conversation convo = convos.get(conversation);
Message msg = new Message();
msg.setSender(user);
msg.setMessage(message);
msg.setTime(new Date());
convo.getMesssages().add(msg);
Set<Conversation> convos = user.getConversations();
Conversation conv = null;
System.out.println("Len: " + convos.size());
for (Conversation con : convos) {
System.out.println(con.getId());
if (con.getId() == conversation) {
conv = con;
break;
}
}
if (conv == null) {
IOHelper.SendResponse(400, "<h1>400 Conversation not found</h1><p>The conversation with the id "
+ conversation + " is not found.</p>", exchange);
return;
}
try (DataProvider provider = new DataProvider()) {
Message msg = new Message();
msg.setSender(user);
msg.setMessage(message);
msg.setTime(new Date());
conv.getMesssages().add(msg);
provider.saveConversation(conv);
System.out.println(conv.getMesssages().size());
} catch (Exception e) {
throw e;
}
IOHelper.SendResponse(200, "Success", exchange);
}