Changed to logger, made a generic save method, ...

This commit is contained in:
Norbi Peti 2016-07-29 13:52:24 +02:00
parent 095269a585
commit 1c60cb6fd5
14 changed files with 144 additions and 128 deletions

View file

@ -1,17 +0,0 @@
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

18
main/resources/log4j2.xml Normal file
View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="MyFile" fileName="logs/app.log">
<PatternLayout
pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
<AppenderRef ref="MyFile" />
</Root>
</Loggers>
</Configuration>

View file

@ -14,6 +14,8 @@ import java.util.UUID;
import java.util.function.Function;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
@ -100,11 +102,11 @@ public class IOHelper {
}
public static void LoginUser(HttpExchange exchange, User user, DataProvider provider) {
System.out.println("Logging in user: " + user);
LogManager.getLogger().log(Level.DEBUG, "Logging in user: " + user);
// provider.SetValues(() ->
// user.setSessionid(UUID.randomUUID().toString()));
user.setSessionid(UUID.randomUUID().toString());
provider.saveUser(user);
provider.save(user);
ZonedDateTime expiretime = ZonedDateTime.now(ZoneId.of("GMT")).plus(Period.of(2, 0, 0));
exchange.getResponseHeaders().add("Set-Cookie",
"user_id=" + user.getId() + "; expires=" + expiretime.format(DateTimeFormatter.RFC_1123_DATE_TIME));

View file

@ -30,7 +30,7 @@ public class Main {
try { // rt.jar Javadoc:
// https://docs.oracle.com/javase/8/docs/jre/api/net/httpserver/spec/
// https://docs.oracle.com/javase/8/docs/api/
System.out.println("Loading database...");
LogManager.getLogger().log(Level.DEBUG, "Loading database...");
try (DataProvider provider = new DataProvider()) {
User user = new User();
user.setName("asd");
@ -39,16 +39,16 @@ public class Main {
user2.setName("Teszt");
user2.setEmail("test2@test.com");
user2.getContacts().add(user);
provider.saveUser(user);
provider.save(user);
List<User> users = provider.getUsers();
user = users.get(0);
user.getContacts().add(user2);
provider.saveUser(user2);
provider.save(user2);
users = provider.getUsers();
user2 = users.get(1);
System.out.println(users);
System.out.println("1st's contact: " + user.getContacts().get(0));
System.out.println("2nd's contact: " + user2.getContacts().get(0));
LogManager.getLogger().log(Level.DEBUG, users);
LogManager.getLogger().log(Level.DEBUG, "1st's contact: " + user.getContacts().get(0));
LogManager.getLogger().log(Level.DEBUG, "2nd's contact: " + user2.getContacts().get(0));
Conversation convo = new Conversation();
convo.getUsers().add(user);
//user.getConversations().add(convo);
@ -65,19 +65,19 @@ public class Main {
msg2.setTime(new Date());
msg2.setMessage("Teszt 2");
convo.getMesssages().add(msg2);
provider.saveConversation(convo);
provider.saveUser(user);
provider.saveUser(user2);
provider.save(convo);
provider.save(user);
provider.save(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);
provider.save(loggedinuser);
provider.save(convo);
}
System.out.println("Starting webserver...");
LogManager.getLogger().log(Level.DEBUG, "Starting webserver...");
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8080), 10);
Reflections rf = new Reflections(
new ConfigurationBuilder().setUrls(ClasspathHelper.forClassLoader(Page.class.getClassLoader()))
@ -97,14 +97,14 @@ public class Main {
}
}
server.start();
System.out.println("Ready... Press Enter to stop.");
LogManager.getLogger().log(Level.DEBUG, "Ready... Press Enter to stop.");
System.in.read();
System.out.println("Stopping...");
LogManager.getLogger().log(Level.DEBUG, "Stopping...");
server.stop(1);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Stopped");
LogManager.getLogger().log(Level.DEBUG, "Stopped");
}
private static void addPage(HttpServer server, Page page) {

View file

@ -18,22 +18,19 @@ public class DataProvider implements AutoCloseable {
emf = Persistence.createEntityManagerFactory("ChatServerPU");
}
public void saveUser(User user) {
save(user);
}
public <T extends ChatDatabaseEntity> void save(T object) {
EntityManager em = null;
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Session s = em.unwrap(Session.class);
s.saveOrUpdate(object);
em.persist(object);
em.getTransaction().commit();
} finally {
em.close();
}
public void saveConversation(Conversation convo) {
save(convo);
}
private void save(Object object) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Session s = em.unwrap(Session.class);
s.saveOrUpdate(object);
em.persist(object);
em.getTransaction().commit();
em.close();
}
public List<User> getUsers() {

View file

@ -0,0 +1,5 @@
package io.github.norbipeti.chat.server.db.domain;
public abstract class ChatDatabaseEntity {
}

View file

@ -8,7 +8,7 @@ import java.util.Set;
import javax.persistence.*;
@Entity
public class Conversation {
public class Conversation extends ChatDatabaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)

View file

@ -5,7 +5,7 @@ import java.util.Date;
import javax.persistence.*;
@Entity
public class Message {
public class Message extends ChatDatabaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)

View file

@ -9,7 +9,7 @@ import javax.persistence.*;
@Entity
@Table(name = "\"User\"")
public class User {
public class User extends ChatDatabaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)

View file

@ -2,6 +2,8 @@ package io.github.norbipeti.chat.server.page;
import java.io.IOException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.jsoup.nodes.Element;
import com.sun.net.httpserver.HttpExchange;
@ -34,9 +36,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());
LogManager.getLogger().log(Level.DEBUG, "Conversations: " + provider.getConversations().size());
Conversation convo = provider.getConversations().get(0);
System.out.println("Messages: " + convo.getMesssages().size());
LogManager.getLogger().log(Level.DEBUG, "Messages: " + convo.getMesssages().size());
for (Message message : convo.getMesssages()) {
Element msgelement = channelmessages.appendElement("div");
Element header = msgelement.appendElement("p");

View file

@ -6,6 +6,9 @@ import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import com.sun.net.httpserver.HttpExchange;
@ -39,9 +42,9 @@ public class MessageAjaxPage extends Page {
int conversation = obj.getInt("conversation");
Set<Conversation> convos = user.getConversations();
Conversation conv = null;
System.out.println("Len: " + convos.size());
LogManager.getLogger().log(Level.DEBUG, "Len: " + convos.size());
for (Conversation con : convos) {
System.out.println(con.getId());
LogManager.getLogger().log(Level.DEBUG, con.getId());
if (con.getId() == conversation) {
conv = con;
break;
@ -57,9 +60,10 @@ public class MessageAjaxPage extends Page {
msg.setSender(user);
msg.setMessage(message);
msg.setTime(new Date());
provider.save(msg);
conv.getMesssages().add(msg);
provider.saveConversation(conv);
System.out.println(conv.getMesssages().size());
provider.save(conv);
LogManager.getLogger().log(Level.DEBUG, "Added conversation's message count: " + conv.getMesssages().size());
} catch (Exception e) {
throw e;
}

View file

@ -40,7 +40,7 @@ public class RegisterAjaxPage extends Page {
user.setEmail(post.getString("email"));
user.setSalt(BCrypt.gensalt()); // http://www.mindrot.org/projects/jBCrypt/
user.setPassword(BCrypt.hashpw(post.getString("pass"), user.getSalt()));
provider.saveUser(user);
provider.save(user);
User managedUser = provider.getUser(user.getId());
IOHelper.LoginUser(exchange, managedUser, provider);
IOHelper.SendResponse(200, "Success", exchange);

View file

@ -1,34 +1,36 @@
package io.github.norbipeti.chat.server.page;
import java.io.File;
import java.io.IOException;
import com.sun.net.httpserver.HttpExchange;
import io.github.norbipeti.chat.server.IOHelper;
public class ScriptsPage extends Page {
@Override
public boolean getDo404() {
return false;
}
@Override
public String GetName() {
return "js/";
}
@Override
public void handlePage(HttpExchange exchange) throws IOException {
if (exchange.getRequestURI().getPath().startsWith("/js/")) {
File jsfile = new File("pages", exchange.getRequestURI().getPath());
if (!jsfile.exists())
IOHelper.SendResponse(404, "<h1>JavaScript file not found</h1>", exchange);
else
IOHelper.SendResponse(200, IOHelper.ReadFile(jsfile), exchange);
}
else
System.out.println(exchange.getRequestURI().getPath());
}
}
package io.github.norbipeti.chat.server.page;
import java.io.File;
import java.io.IOException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import com.sun.net.httpserver.HttpExchange;
import io.github.norbipeti.chat.server.IOHelper;
public class ScriptsPage extends Page {
@Override
public boolean getDo404() {
return false;
}
@Override
public String GetName() {
return "js/";
}
@Override
public void handlePage(HttpExchange exchange) throws IOException {
if (exchange.getRequestURI().getPath().startsWith("/js/")) {
File jsfile = new File("pages", exchange.getRequestURI().getPath());
if (!jsfile.exists())
IOHelper.SendResponse(404, "<h1>JavaScript file not found</h1>", exchange);
else
IOHelper.SendResponse(200, IOHelper.ReadFile(jsfile), exchange);
} else
LogManager.getLogger().log(Level.DEBUG, exchange.getRequestURI().getPath());
}
}

View file

@ -1,35 +1,38 @@
package io.github.norbipeti.chat.server.page;
import java.io.File;
import java.io.IOException;
import com.sun.net.httpserver.HttpExchange;
import io.github.norbipeti.chat.server.IOHelper;
public class StylePage extends Page {
@Override
public boolean getDo404() {
return false;
}
@Override
public String GetName() {
return "css/";
}
@Override
public void handlePage(HttpExchange exchange) throws IOException {
if (exchange.getRequestURI().getPath().startsWith("/css/")) {
File cssfile = new File("pages", exchange.getRequestURI().getPath());
if (!cssfile.exists())
IOHelper.SendResponse(404, "<h1>CSS file not found</h1>", exchange);
else {
exchange.getResponseHeaders().add("Content-Type", "text/css");
IOHelper.SendResponse(200, IOHelper.ReadFile(cssfile), exchange);
}
} else
System.out.println(exchange.getRequestURI().getPath());
}
}
package io.github.norbipeti.chat.server.page;
import java.io.File;
import java.io.IOException;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import com.sun.net.httpserver.HttpExchange;
import io.github.norbipeti.chat.server.IOHelper;
public class StylePage extends Page {
@Override
public boolean getDo404() {
return false;
}
@Override
public String GetName() {
return "css/";
}
@Override
public void handlePage(HttpExchange exchange) throws IOException {
if (exchange.getRequestURI().getPath().startsWith("/css/")) {
File cssfile = new File("pages", exchange.getRequestURI().getPath());
if (!cssfile.exists())
IOHelper.SendResponse(404, "<h1>CSS file not found</h1>", exchange);
else {
exchange.getResponseHeaders().add("Content-Type", "text/css");
IOHelper.SendResponse(200, IOHelper.ReadFile(cssfile), exchange);
}
} else
LogManager.getLogger().log(Level.DEBUG, exchange.getRequestURI().getPath());
}
}