Commit bad7827d authored by Jonathan Sudibya's avatar Jonathan Sudibya
Browse files

Merge branch 'message-controler'

parents 93ce4e96 5c6643ba
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Connection;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Jonathan
*/
public class ConnectionHandler {
private Socket connection;
public ConnectionHandler(String address,int port)
{
try {
connection = new Socket(address,port);
} catch (IOException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void start(){
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Connection;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author Jonathan
*/
public class Listener implements Runnable {
private Socket connection;
private Vector<JSONObject> data;
private Thread t;
private boolean active;
public Listener(Socket _connection)
{
connection = _connection;
data = new Vector<>();
active = true;
}
@Override
public void run() {
JSONParser parser = new JSONParser();
while (active){
try {
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
data.add((JSONObject) parser.parse(inFromServer.readLine()));
} catch (IOException ex) {
Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(Listener.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void start(){
if (t != null){
t = new Thread(this,"Client Listener");
t.start();
}
}
public void setActive(boolean _active)
{
active = _active;
}
public boolean isDataEmpty()
{
return data.isEmpty();
}
public JSONObject getFirstData()
{
return data.remove(0);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Connection;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
/**
*
* @author Jonathan
*/
public class Sender implements Runnable {
private JSONObject data;
private Socket connectionSocket;
private boolean active;
private Thread t;
public Sender(Socket _connection)
{
connectionSocket = _connection;
active = true;
}
@Override
public void run()
{
while(active)
{
if (!data.isEmpty()){
try {
DataOutputStream outToServer = new DataOutputStream(connectionSocket.getOutputStream());
outToServer.write(data.toJSONString().getBytes(Charset.forName("UTF-8")));
data.clear();
} catch (IOException ex) {
Logger.getLogger(Sender.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void setActive(boolean a)
{
active = a;
}
public void setData(JSONObject _data)
{
data = _data;
}
public boolean isDataEmpty()
{
return data.isEmpty();
}
public void start()
{
if (t != null)
{
t = new Thread(this,"Client Sender");
t.start();
}
}
}
......@@ -18,16 +18,17 @@ import static org.json.simple.JSONValue.parse;
class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
System.out.println(InetAddress.getLocalHost().getAddress());
// String sentence;
// String modifiedSentence;
// BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
// Socket clientSocket = new Socket("localhost", 6789);
// DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
// BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// sentence = inFromUser.readLine();
// outToServer.writeBytes(sentence + '\n');
// modifiedSentence = inFromServer.readLine();
// System.out.println("FROM SERVER: " + modifiedSentence);
// clientSocket.close();
}
}
package Controller;
import Model.Client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
/*
* To change this license header, choose License Headers in Project Properties.
......@@ -23,13 +33,15 @@ public class ConnectionHandler implements Runnable {
private Vector<Client> clients;
private boolean active;
private int globalID;
private int serverSocket;
public ConnectionHandler(){
threadName = "Connection-Handler";
active = true;
globalID = 0;
serverSocket = 6789;
try {
welcomeSocket = new ServerSocket(6789);
welcomeSocket = new ServerSocket(serverSocket);
clients = new Vector<>();
} catch (IOException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
......@@ -40,15 +52,23 @@ public class ConnectionHandler implements Runnable {
@Override
public void run() {
System.out.println("Running thread " + threadName);
while(active){
try {
clients.add(new Client(globalID,welcomeSocket.accept()));
clients.lastElement().start();
globalID++;
} catch (IOException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connecting to tracker server...");
if (connectTracker())
{
System.out.println("Connection to tracker server successfull... Ready to recieve connection!");
while(active){
try {
clients.add(new Client(globalID,welcomeSocket.accept()));
clients.lastElement().start();
globalID++;
} catch (IOException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
else {
System.out.println("Error, Failed to connect server.. ");
}
System.out.println("Thread " + threadName + " exiting...");
}
......@@ -63,4 +83,31 @@ public class ConnectionHandler implements Runnable {
{
active = _active;
}
private boolean connectTracker()
{
boolean ret;
try {
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket newServer = new Socket("167.205.32.46", 8000);
DataOutputStream outToTracker = new DataOutputStream(newServer.getOutputStream());
BufferedReader inFromTracker = new BufferedReader(new InputStreamReader(newServer.getInputStream()));
JSONObject join = new JSONObject();
join.put("method", "join");
join.put("ip",InetAddress.getLocalHost().getHostAddress());
join.put("port",6789);
sentence = join.toJSONString();
outToTracker.write(sentence.getBytes(Charset.forName("UTF-8")));
modifiedSentence = inFromTracker.readLine();
System.out.println("FROM TRACKER: " + modifiedSentence);
newServer.close();
ret = true;
} catch (IOException ex) {
ret = false;
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return ret;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controller;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author Jonathan
*/
public class MemoryCached implements Runnable {
private Vector<JSONObject> currentData;
private Vector<JSONObject> dumpData;
private Thread t;
public MemoryCached(){
currentData = new Vector<>();
dumpData = new Vector<>();
}
@Override
public void run() {
FileReader read;
FileWriter write;
String line = null;
JSONParser parser = new JSONParser();
JSONObject data = null;
JSONArray array = null;
try {
read = new FileReader("UserData.JSON"); //open dump and try to read data
if (read != null){ // file is present
BufferedReader bufferReader = new BufferedReader(read);
while ((line = bufferReader.readLine()) != null)
{
}
bufferReader.close();
if (line != null) // data is present
{
Object obj = parser.parse(line);
if (obj != null){
data = (JSONObject) obj;
System.out.println("Message :" + data.toJSONString());
array = (JSONArray) data.get("user");
while (!array.isEmpty()){
dumpData.add((JSONObject)array.remove(0));
}
}
}
}
if (dumpData.isEmpty()) // if data is empty
{
dumpData = currentData;
currentData.clear();
}
else // if data is present update data
{
int i =0;
int j =0;
boolean found = false;
while (!currentData.isEmpty())
{
if (i >= dumpData.size()) // if the data is not is not in the file
{
while (!currentData.isEmpty()){
dumpData.add(currentData.remove(0));
}
}
else{ // checking data with the current dumpData.
j = 0;
found = false;
while(j < currentData.size() && !found)
{
if (dumpData.get(i).get("id") == currentData.get(j).get("id"))
{
dumpData.get(i).put("inventory", currentData.get(i).get("inventory"));
dumpData.get(i).put("location", currentData.get(i).get("location"));
found = true;
currentData.remove(j);
}
else
{
j++;
}
}
i++;
}
}
}
array.clear();
while (!dumpData.isEmpty())
{
array.add(dumpData.remove(0));
}
write = new FileWriter("UserData.JSON");
data.put("user", array);
write.write(data.toJSONString());
write.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MemoryCached.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MemoryCached.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(MemoryCached.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void start(){
if (t == null)
{
t = new Thread("DB-Sync");
t.start();
}
else{
System.err.println("Error opening or creating File!\nProcess will terminate!");
}
}
/**
* Add an entire vector of JSONObject. WARNING : It will override the entire vector.
* @param data
*/
public void addData(Vector<JSONObject> data)
{
currentData = data;
}
/**
* Add or update (if exist) a data to the vector.
* @param data
*/
public void addData(JSONObject data)
{
int i = 0;
boolean found = false;
while(i < currentData.size() && !found) //if found update new data
{
if (currentData.get(i).get("id") == data.get("id"))
{
found = true;
currentData.get(i).put("inventory", data.get("inventory"));
currentData.get(i).put("location", data.get("location"));
}
else
{
i++;
}
}
if (!found) //add new data
{
currentData.add(data);
}
}
}
......@@ -3,7 +3,7 @@
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package crudDB;
package Method;
import java.io.File;
import java.io.FileReader;
......
package Model;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
......@@ -7,7 +8,6 @@ import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
......@@ -21,13 +21,12 @@ import org.json.simple.parser.ParseException;
*
* @author Jonathan
*/
class Client implements Runnable {
public class Client implements Runnable {
private int ID;
private String threadName;
private Socket connectionSocket;
private Thread t;
private boolean active;
private String clientSentence;
private String capitalizedSentence;
public Client(int _id,Socket _client)
......@@ -46,21 +45,34 @@ class Client implements Runnable {
while(active)
{
DataOutputStream outToClient = null;
BufferedReader inFromClient = null;
InputStreamReader inFromClient = null;
String clientSentence = "";
int buf;
try {
inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
if (clientSentence != null){
System.out.println("Client ip "+threadName+ " :" +connectionSocket.getRemoteSocketAddress());
connectionSocket.setSoTimeout(3000);
inFromClient = new InputStreamReader(connectionSocket.getInputStream());
while ((buf=inFromClient.read()) != -1){
char c = (char)buf; //converting to char
clientSentence += Character.toString(c); //added to the sentence and convert char to String.
}
System.out.println("Received From "+connectionSocket.getInetAddress().getHostAddress()+ ": " + clientSentence);
if (!clientSentence.equals("")){
outToClient = new DataOutputStream(connectionSocket.getOutputStream());
System.out.println("Received: " + clientSentence);
Object obj = parser.parse(clientSentence);
if (obj != null){
JSONObject array = (JSONObject) obj;
JSONObject data = (JSONObject) obj;
System.out.println("Message :" + data.toJSONString());
}
capitalizedSentence = clientSentence.toUpperCase() + '\n';
JSONObject correct = new JSONObject();
correct.put("status", "ok");
capitalizedSentence = correct.toJSONString();
outToClient.writeBytes(capitalizedSentence);
connectionSocket.close();
active = false;
}
else{
System.out.println("Null message detected");
active = false;
}
} catch (IOException ex) {
......@@ -70,7 +82,7 @@ class Client implements Runnable {
} finally {
try {
inFromClient.close();
outToClient.close();
//outToClient.close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import java.util.Vector;
import org.json.simple.JSONObject;
/**
*
* @author Jonathan
*/
public final class MessageProcessor {
public static JSONObject getReply(JSONObject data)
{
JSONObject ret = new JSONObject();
return ret;
}
private JSONObject statusOK()
{
JSONObject ret = new JSONObject();
ret.put("status", "ok");
return ret;
</