Commit 10046617 authored by Kevin's avatar Kevin
Browse files

merging lagi

parent d6b31fed
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.annotation.adapters.HexBinaryAdapter;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/*
* 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.
*/
/**
*
* @author Jonathan
*/
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;
private String username;
private String token;
public Client(int _id,Socket _client)
{
ID = _id;
connectionSocket = _client;
threadName = "Client-Listener-"+ID;
active = true;
System.out.println("Created thread " + threadName);
}
@Override
public void run() {
JSONParser parser = new JSONParser();
System.out.println("Running thread " + threadName);
while(active)
{
DataOutputStream outToClient = null;
BufferedReader inFromClient = null;
try {
inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
clientSentence = inFromClient.readLine();
if (clientSentence != null){
outToClient = new DataOutputStream(connectionSocket.getOutputStream());
//System.out.println("Received: " + clientSentence);
Object obj = parser.parse(clientSentence);
String response = "{ \"status\" : \"ok\" }";
if (obj != null){
JSONObject array = (JSONObject) obj;
String method = (String) array.get("method");
switch(method) {
case "login" : {
try {
response = this.login(array);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
case "signup" : {
response = this.signUp(array);
}
default : {
//senderror
}
}
System.out.println(response);
//MapHandler.load();
}
//System.out.println(clientSentence);
//outToClient.writeBytes(clientSentence);
//capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(response);
}
else{
active = false;
}
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inFromClient.close();
outToClient.close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
System.out.println("Thread " + threadName + " exiting...");
}
//feed = username client + timestamp
public void generateToken(String feed) throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
token = (new HexBinaryAdapter()).marshal(md5.digest(feed.getBytes()));
}
public void start(){
if (t == null)
{
t = new Thread(this, threadName);
t.start();
}
}
public String login(JSONObject obj) throws NoSuchAlgorithmException {
username = (String) obj.get("username");
String password = (String) obj.get("password");
JSONObject res = new JSONObject();
res.put("status","error");
if(DBHandler.isUserValid(username,password)) {
int[] pos = DBHandler.getPosition(username);
String timestamp = Long.toString(System.currentTimeMillis());
this.generateToken(username+timestamp);
ConnectionHandler.tokenMap.put(token,username);
res.put("status","ok");
res.put("token",token);
res.put("x",pos[0]);
res.put("y",pos[1]);
res.put("time",timestamp);
}
else {
res.put("status","fail");
res.put("description", "username/password combination is not found");
}
return res.toString();
}
public String signUp(JSONObject obj) {
String username = (String) obj.get("username");
String password = (String) obj.get("password");
JSONObject res = new JSONObject();
res.put("status","error");
if(DBHandler.isUserExists(username)) {
res.put("status","fail");
res.put("description","username exists");
}
else {
DBHandler.signUp(username, password);
res.put("status","ok");
}
return res.toString();
}
}
import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* 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.
*/
/**
*
* @author Jonathan
*/
public class ConnectionHandler implements Runnable {
private Thread t;
private String threadName;
private ServerSocket welcomeSocket;
private Vector<Client> clients;
private boolean active;
private int globalID;
public static Map<String,String> tokenMap;
public ConnectionHandler(){
threadName = "Connection-Handler";
active = true;
globalID = 0;
tokenMap = new HashMap<String,String>();
try {
welcomeSocket = new ServerSocket(6789);
clients = new Vector<>();
} catch (IOException ex) {
Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Created thread " + threadName);
}
@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("Thread " + threadName + " exiting...");
}
public void start(){
if (t == null){
t = new Thread(this, threadName);
t.start();
}
}
public void setActive(boolean _active)
{
active = _active;
}
}
...@@ -9,6 +9,8 @@ import java.net.InetAddress; ...@@ -9,6 +9,8 @@ import java.net.InetAddress;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.net.Socket; import java.net.Socket;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector; import java.util.Vector;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
...@@ -34,10 +36,13 @@ public class ConnectionHandler implements Runnable { ...@@ -34,10 +36,13 @@ public class ConnectionHandler implements Runnable {
private int globalID; private int globalID;
private int serverSocket; private int serverSocket;
public static Map<String,String> tokenMap;
public ConnectionHandler(){ public ConnectionHandler(){
threadName = "Connection-Handler"; threadName = "Connection-Handler";
active = true; active = true;
globalID = 0; globalID = 0;
tokenMap = new HashMap<String,String>();
serverSocket = 6789; serverSocket = 6789;
try { try {
welcomeSocket = new ServerSocket(serverSocket); welcomeSocket = new ServerSocket(serverSocket);
......
package Default;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.DB; import com.mongodb.DB;
...@@ -83,17 +85,6 @@ public class DBHandler { ...@@ -83,17 +85,6 @@ public class DBHandler {
while(cursor.hasNext()) { while(cursor.hasNext()) {
BasicDBObject curObj = new BasicDBObject(); BasicDBObject curObj = new BasicDBObject();
curObj = (BasicDBObject) cursor.next(); curObj = (BasicDBObject) cursor.next();
/*itemArr[0] = Integer.parseInt(cursor.next().get("r11").toString());
itemArr[1] = Integer.parseInt(cursor.next().get("r12").toString());
itemArr[2] = Integer.parseInt(cursor.next().get("r13").toString());
itemArr[3] = Integer.parseInt(cursor.next().get("r14").toString());
itemArr[4] = Integer.parseInt(cursor.next().get("r21").toString());
itemArr[5] = Integer.parseInt(cursor.next().get("r22").toString());
itemArr[6] = Integer.parseInt(cursor.next().get("r23").toString());
itemArr[7] = Integer.parseInt(cursor.next().get("r31").toString());
itemArr[8] = Integer.parseInt(cursor.next().get("r32").toString());
itemArr[9] = Integer.parseInt(cursor.next().get("r41").toString());*/
itemArr[0] = Integer.parseInt(curObj.get("r11").toString()); itemArr[0] = Integer.parseInt(curObj.get("r11").toString());
itemArr[1] = Integer.parseInt(curObj.get("r12").toString()); itemArr[1] = Integer.parseInt(curObj.get("r12").toString());
itemArr[2] = Integer.parseInt(curObj.get("r13").toString()); itemArr[2] = Integer.parseInt(curObj.get("r13").toString());
......
package Default;
/* /*
* To change this license header, choose License Headers in Project Properties. * To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates * To change this template file, choose Tools | Templates
...@@ -8,8 +10,10 @@ ...@@ -8,8 +10,10 @@
* *
* @author Jonathan * @author Jonathan
*/ */
package Default;
import Controller.ConnectionHandler; import Controller.ConnectionHandler;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import java.io.*; import java.io.*;
import java.net.*; import java.net.*;
import java.util.Vector; import java.util.Vector;
...@@ -20,16 +24,19 @@ import org.json.simple.JSONObject; ...@@ -20,16 +24,19 @@ import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
class TCPServer { import java.util.List;
import java.util.Set;
public ServerSocket welcomeSocket; import static java.util.concurrent.TimeUnit.SECONDS;
public boolean active; class TCPServer {
public int globalID;
public Socket conSocket;
public String trackerSentence;
public static void main(String argv[]) throws Exception { public static void main(String argv[]) throws Exception {
ConnectionHandler CH = new ConnectionHandler(); //ConnectionHandler CH = new ConnectionHandler();
CH.start(); //CH.start();
DBHandler.initialize();
ConnectionHandler CH = new ConnectionHandler();
CH.start();
} }
} }
package Model; package Model;
import Controller.ConnectionHandler;
import Default.DBHandler;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStreamReader;
...@@ -85,16 +87,34 @@ public class Client implements Runnable { ...@@ -85,16 +87,34 @@ public class Client implements Runnable {
if (obj != null) { if (obj != null) {
JSONObject data = (JSONObject) obj; JSONObject data = (JSONObject) obj;
clientSentence = ""; clientSentence = "";
// Buat ngetes offer // Buat ngetes offer
if (data.containsKey("method")) { if (data.containsKey("method")) {
if (data.get("method").toString().equals("offer")) { hasil = "{ \"status\" : \"ok\" }";
// Ganti "kevin" dengan token username String method = (String) data.get("method");
hasil = EndpointMethod.offer("kevin", data.get("offered_item"), data.get("n1"), data.get("demanded_item"), data.get("n2")); switch (method) {
outToClient.write(hasil.getBytes(Charset.forName("UTF-8"))); case "login": {
} else if (data.get("method").toString().equals("tradebox")) { try {
hasil=EndpointMethod.tradebox("kevin"); hasil = this.login(data);
outToClient.write(hasil.getBytes(Charset.forName("UTF-8"))); } catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
case "signup": {
hasil = this.signUp(data);
}
case "offer": {
hasil = EndpointMethod.offer("kevin", data.get("offered_item"), data.get("n1"), data.get("demanded_item"), data.get("n2"));
}
case "tradebox": {
hasil = EndpointMethod.tradebox("kevin");
}
default: {
//senderror
}
} }
outToClient.write(hasil.getBytes(Charset.forName("UTF-8")));
} }
} }
connectionSocket.close(); connectionSocket.close();
...@@ -134,4 +154,41 @@ public class Client implements Runnable { ...@@ -134,4 +154,41 @@ public class Client implements Runnable {
t.start(); t.start();
} }
} }
public String login(JSONObject obj) throws NoSuchAlgorithmException {
username = (String) obj.get("username");
String password = (String) obj.get("password");
JSONObject res = new JSONObject();
res.put("status", "error");
if (DBHandler.isUserValid(username, password)) {
int[] pos = DBHandler.getPosition(username);
String timestamp = Long.toString(System.currentTimeMillis());
this.generateToken(username + timestamp);
ConnectionHandler.tokenMap.put(token, username);
res.put("status", "ok");
res.put("token", token);
res.put("x", pos[0]);
res.put("y", pos[1]);
res.put("time", timestamp);
} else {
res.put("status", "fail");
res.put("description", "username/password combination is not found");
}
return res.toString();
}
public String signUp(JSONObject obj) {
String username = (String) obj.get("username");
String password = (String) obj.get("password");
JSONObject res = new JSONObject();
res.put("status", "error");
if (DBHandler.isUserExists(username)) {
res.put("status", "fail");
res.put("description", "username exists");
} else {
DBHandler.signUp(username, password);
res.put("status", "ok");
}
return res.toString();
}
} }
/*
* 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.
*/
/**
*
* @author Jonathan
*/
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import java.io.*;
import java.net.*;
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;
import java.util.List;
import java.util.Set;
import static java.util.concurrent.TimeUnit.SECONDS;
class TCPServer {
public ServerSocket welcomeSocket;
public Vector<Client> clients;
public boolean active;
public int globalID;
public Socket conSocket;
public String trackerSentence;
public TCPServer() {
active = true;
globalID = 0;
try {
welcomeSocket = new ServerSocket(2000);
} catch (IOException ex) {
Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String serverStatus() throws IOException {
JSONObject resultJson = new JSONObject();
JSONParser parser = new JSONParser();
DataOutputStream outToTracker = null;
BufferedReader inFromTracker = null;
System.out.println("Nunggu koneksi");
conSocket = welcomeSocket.accept();
System.out.println("Koneksi sudah ada");
inFromTracker = new BufferedReader(new InputStreamReader(conSocket.getInputStream()));
outToTracker = new DataOutputStream(conSocket.getOutputStream());
trackerSentence = inFromTracker.readLine();
System.out.println("Received: " + trackerSentence);
// while (active) {
// try {
// int i = 0;
// System.out.println("trackerSentence telah terbaca");
// while (i < 10) {
// trackerSentence = inFromTracker.readLine();
// System.out.println("Received: " + trackerSentence);
// i++;
// }
// if (trackerSentence != null) {
// System.out.println("TrackerSentence: " + trackerSentence);
// Object obj = parser.parse(trackerSentence);
// if (obj != null) {
// JSONObject inJson = (JSONObject) obj;
// if (inJson.get("method").toString().equalsIgnoreCase("serverStatus")) {
// JSONArray server_list_active = new JSONArray();
// server_list_active = (JSONArray) inJson.get("server");
// System.out.println(server_list_active);
// resultJson.put("status", "ok");
// outToTracker.write(resultJson.toString().getBytes());
// return resultJson.toString();
// }
// }
// } else {
// active = false;
// }
// } catch (IOException ex) {
// Logger.getLogger(ConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
// } catch (ParseException ex) {
// Logger.getLogger(TCPServer.class.getName()).log(Level.SEVERE, null, ex);
// }
// }
resultJson.put("status", "error");
return resultJson.toString();
}
public void setActive(boolean _active) {
active = _active;
}
public static void join() throws IOException {
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()));
sentence = inFromUser.readLine();
outToTracker.write(sentence.getBytes());
modifiedSentence = inFromTracker.readLine();
System.out.println("FROM TRACKER: " + modifiedSentence);
newServer.close();
}
// public static String serverStatus(Object inObj) {
// JSONObject resultJson = new JSONObject();
// if (inObj != null) {
// JSONObject inJson = (JSONObject) inObj;
// if (inJson.containsKey("method")) {
// if (inJson.get("method").toString().equalsIgnoreCase("serverStatus")) {
// JSONArray server_list_active = new JSONArray();
// server_list_active = (JSONArray) inJson.get("server");
// System.out.println(server_list_active);
// resultJson.put("status", "ok");
// }
// }
// }
// resultJson.put("status", "error");
// return resultJson.toString();
// }
public static void main(String argv[]) throws Exception {
//ConnectionHandler CH = new ConnectionHandler();
//CH.start();
/*String hasil;
join();
TCPServer tes = new TCPServer();