Commit b769eb2a authored by adwisatya's avatar adwisatya
Browse files

Cleaning Up The Code

parent f12af3f9
......@@ -3,10 +3,7 @@
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
<open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
<group>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/client/TheAlchemistClient/src/thealchemist/engine/Connection.java</file>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/client/TheAlchemistClient/src/thealchemist/engine/Main.java</file>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/client/TheAlchemistClient/src/thealchemist/gui/AlcLogon.java</file>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/client/TheAlchemistClient/src/thealchemist/engine/Response.java</file>
</group>
</open-files>
</project-private>
#Sun, 26 Apr 2015 20:27:08 +0700
#Mon, 27 Apr 2015 00:13:24 +0700
C\:\\Users\\adwisatya\\Documents\\Semester\ 6\\Tugas\\IF3230\ Sister\\IF3230-Tugas-Besar-Sister-2015\\src\\server=
......@@ -4,7 +4,6 @@
<open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
<group>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/server/src/thealchemist/Client.java</file>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/server/src/thealchemist/Database.java</file>
<file>file:/C:/Users/adwisatya/Documents/Semester%206/Tugas/IF3230%20Sister/IF3230-Tugas-Besar-Sister-2015/src/server/src/thealchemist/TCPServer.java</file>
</group>
</open-files>
......
{"name" : "Bandar Behari","width" : 4,"height" : 4,"map" :[["R13", "R13", "R13", "R13"],["R13", "R13", "R14", "R14"],["R13", "R14", "R14", "R14"],["R13", "R14", "R14", "R14"]]}
......@@ -58,7 +58,10 @@ public class Client extends Thread{
public ArrayList<String> servers;
public String offers;
/* External Class */
Utility utility = new Utility();
Database database = new Database();
public Client(Socket c) throws IOException{
connectionSocket = c;
}
......@@ -109,13 +112,13 @@ public class Client extends Thread{
public void checkCommand(String cmd) throws IOException, NoSuchAlgorithmException, JSONException {
cmdJoin();
System.out.println("Request: " + cmd);
if(isJSONValid(cmd)){
switch (JSONtoString("method",cmd)){
if(utility.isJSONValid(cmd)){
switch (utility.JSONtoString("method",cmd)){
case "getServer":
System.out.println(database.getServers().toString());
break;
case "serverStatus":
cmdServerStatus(JSONtoString("server",cmd));
cmdServerStatus(utility.JSONtoString("server",cmd));
break;
/* 1 */
case "join" :
......@@ -123,66 +126,61 @@ public class Client extends Thread{
break;
case "signup" :
cmdSignUp(JSONtoString("username",cmd),JSONtoString("password",cmd));
cmdSignUp(utility.JSONtoString("username",cmd),utility.JSONtoString("password",cmd));
break;
/* 3 */
case "login" :
cmdLogin(JSONtoString("username",cmd),JSONtoString("password",cmd));
cmdLogin(utility.JSONtoString("username",cmd),utility.JSONtoString("password",cmd));
break;
/* 4 */
case "inventory":
cmdInventory(JSONtoString("token",cmd));
cmdInventory(utility.JSONtoString("token",cmd));
break;
/* 5 */
case "mixitem":
cmdMixitem(JSONtoString("token",cmd),JSONtoString("item1",cmd),JSONtoString("item2",cmd));
cmdMixitem(utility.JSONtoString("token",cmd),utility.JSONtoString("item1",cmd),utility.JSONtoString("item2",cmd));
break;
/* 6 */
case "map":
cmdMap(JSONtoString("token",cmd));
cmdMap(utility.JSONtoString("token",cmd));
break;
/* 7 */
case "move":
cmdMove(JSONtoString("token",cmd),JSONtoString("x",cmd),JSONtoString("y",cmd));
cmdMove(utility.JSONtoString("token",cmd),utility.JSONtoString("x",cmd),utility.JSONtoString("y",cmd));
break;
/* 8 */
case "field":
cmdField(JSONtoString("token",cmd));
cmdField(utility.JSONtoString("token",cmd));
break;
/* 9 */
case "offer" :
cmdOffer(JSONtoString("token",cmd), Integer.parseInt(JSONtoString("offered_item",cmd)), Integer.parseInt(JSONtoString("n1",cmd)), Integer.parseInt(JSONtoString("demanded_item",cmd)), Integer.parseInt(JSONtoString("n2",cmd)));
cmdOffer(utility.JSONtoString("token",cmd), Integer.parseInt(utility.JSONtoString("offered_item",cmd)), Integer.parseInt(utility.JSONtoString("n1",cmd)), Integer.parseInt(utility.JSONtoString("demanded_item",cmd)), Integer.parseInt(utility.JSONtoString("n2",cmd)));
break;
/* 10 */
case "tradebox":
cmdTradebox(JSONtoString("token",cmd));
cmdTradebox(utility.JSONtoString("token",cmd));
break;
/* 11 */
case "sendfind":
cmdSendFind(JSONtoString("token",cmd), Integer.parseInt(JSONtoString("item",cmd)));
cmdSendFind(utility.JSONtoString("token",cmd), Integer.parseInt(utility.JSONtoString("item",cmd)));
break;
/* 12 belum */
case "findoffer":
cmdFindOffer(new Integer(JSONtoString("itemid",cmd)));
cmdFindOffer(new Integer(utility.JSONtoString("itemid",cmd)));
break;
case "13": System.out.println(cmdSendAccept("ece63df163ce1948008064c006f4900d","ece63df163ce1948008064c006f4900d"));
break;
case "14": System.out.println(cmdAccept("ece63df163ce1948008064c006f4900d"));
break;
case "fetchitem":
cmdFetchItem(JSONtoString("token",cmd), JSONtoString("offer_token",cmd));
cmdFetchItem(utility.JSONtoString("token",cmd), utility.JSONtoString("offer_token",cmd));
break;
case "canceloffer":
cmdCancelOffer(JSONtoString("token",cmd), JSONtoString("offer_token",cmd));
cmdCancelOffer(utility.JSONtoString("token",cmd), utility.JSONtoString("offer_token",cmd));
break;
}
}
}
public String JSONtoString(String param, String JSON) throws JSONException{
JSONObject jsonObj = new JSONObject(JSON);
return jsonObj.getString(param);
}
public void cmdServerStatus(String request){
try {
......@@ -204,7 +202,7 @@ public class Client extends Thread{
Socket miniSocket = new Socket(URL,defPort);
JSONObject obj = new JSONObject();
obj.put("method", "join");
obj.put("ip", getIP());
obj.put("ip", utility.getIP());
obj.put("port", new Integer(myPort));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(miniSocket.getOutputStream())));
......@@ -248,10 +246,10 @@ public class Client extends Thread{
try {
if(database.Login(username, password)){
obj.put("status", "ok");
obj.put("token", toMD5(username));
obj.put("token", utility.toMD5(username));
obj.put("x", 0);
obj.put("y", 0);
obj.put("time",new Long(getTime()));
obj.put("time",new Long(utility.getTime()));
}else{
obj.put("status", "fail");
obj.put("description", "username/password combination is not found");
......@@ -275,7 +273,7 @@ public class Client extends Thread{
/* Sukses */
public void cmdInventory(String token) throws IOException, NoSuchAlgorithmException, JSONException{
JSONObject obj = new JSONObject();
if(isJSONValid(database.Inventory(token).toString())){
if(utility.isJSONValid(database.Inventory(token).toString())){
obj.put("status","ok");
obj.put("inventory",database.Inventory(token));
}else{
......@@ -509,35 +507,7 @@ public class Client extends Thread{
}
sendToClient(obj.toString());
}
public String toMD5(String input) throws NoSuchAlgorithmException{
/* taken from http://www.mkyong.com/java/java-md5-hashing-example/ */
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include @Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
public String getNameItem(int id) {
String name = "";
switch(id) {
......@@ -558,31 +528,6 @@ public class Client extends Thread{
return name;
}
// methods for mix item
public boolean isJumlahTigaLebih (int jumlah) {
return (jumlah >= 3);
}
public int mixItem(int item1, int item2) {
int result;
if((item1 == 0 && item2 == 1) || (item1 == 1 && item2 == 0)) {
result = 4;
} else if((item1 == 1 && item2 == 2) || (item1 == 2 && item2 == 1)) {
result = 5;
} else if((item1 == 2 && item2 == 3) || (item1 == 3 && item2 == 2)) {
result = 6;
} else if((item1 == 4 && item2 == 5) || (item1 == 5 && item2 == 4)) {
result = 7;
} else if((item1 == 5 && item2 == 6) || (item1 == 6 && item2 == 5)) {
result = 8;
} else if((item1 == 7 && item2 == 8) || (item1 == 8 && item2 == 7)) {
result = 9;
} else {
System.out.println("id not exist!");
result = -1;
}
return result;
}
// methods for move
// apakah move player valid satu kotak
public boolean isMoveValid(int currX, int currY, int destX, int destY) {
......@@ -604,38 +549,7 @@ public class Client extends Thread{
}
return pass;
}
public String getIP(){
// String myIP = "";
// String ip;
// try {
// Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
// while (interfaces.hasMoreElements()) {
// NetworkInterface iface = interfaces.nextElement();
// // filters out 127.0.0.1 and inactive interfaces
// if (iface.isLoopback() || !iface.isUp())
// continue;
//
// Enumeration<InetAddress> addresses = iface.getInetAddresses();
// while(addresses.hasMoreElements()) {
// InetAddress addr = addresses.nextElement();
// ip = addr.getHostAddress();
// if(ip.contains("167.205.")){
// myIP = ip;
// }
// }
// }
// } catch (SocketException e) {
// throw new RuntimeException(e);
// }
// return myIP;
String addr = "";
try {
addr = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
return addr;
}
public void loadMap(){
String filename = "map.json";
File f = new File("file.json");
......@@ -645,20 +559,5 @@ public class Client extends Thread{
System.out.println("tidak ada");
}
}
public long getTime(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
simpleDateFormat.setTimeZone(TimeZone.getDefault());
Date now = new Date();
Calendar calendar = Calendar.getInstance();
String strDate = simpleDateFormat.format(now);
try {
calendar.setTime(simpleDateFormat.parse(strDate));
}catch(ParseException e){
e.printStackTrace();
}
return (calendar.getTimeInMillis()+30000)/1000;
}
}
......@@ -30,6 +30,8 @@ public class Database {
static final String username = "root";
static final String password = "";
Utility utility = new Utility();
public int AddUser(String _username, String _password) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
Connection conn = null;
PreparedStatement statement = null;
......@@ -41,7 +43,7 @@ public class Database {
statement.setString(1,_username);
statement.setString(2,_password);
try {
statement.setString(3, toMD5(_username));
statement.setString(3, utility.toMD5(_username));
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
}
......@@ -397,7 +399,7 @@ public class Database {
conn.close();
try {
obj.put("status","ok");
obj.put("time",new Long(getTime()));
obj.put("time",new Long(utility.getTime()));
} catch (JSONException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
try {
......@@ -473,7 +475,7 @@ public class Database {
statement.setInt(3,_n1);
statement.setInt(4,_demanded_item);
statement.setInt(5,_n2);
statement.setString(6,toMD5(_token + Integer.toString(temp))); // value of offer token
statement.setString(6,utility.toMD5(_token + Integer.toString(temp))); // value of offer token
rs = statement.executeUpdate();
System.out.println(rs);
statement.close();
......@@ -527,7 +529,7 @@ public class Database {
data.put(rs.getInt("demanded_item"));
data.put(rs.getInt("n2"));
data.put(rs.getBoolean("available"));
data.put(toMD5(_token+rs.getString("id_offer"))); // value of token_offer
data.put(utility.toMD5(_token+rs.getString("id_offer"))); // value of token_offer
json.put(data);
}
statement.close();
......@@ -575,38 +577,6 @@ public class Database {
}
return rs;
}
public String toMD5(String input) throws NoSuchAlgorithmException{
/* taken from http://www.mkyong.com/java/java-md5-hashing-example/ */
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public String JSONtoString(String param, String JSON) throws JSONException{
JSONObject jsonObj = new JSONObject(JSON);
return jsonObj.getString(param);
}
public long getTime(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
simpleDateFormat.setTimeZone(TimeZone.getDefault());
java.util.Date now = new java.util.Date();
Calendar calendar = Calendar.getInstance();
String strDate = simpleDateFormat.format(now);
try {
calendar.setTime(simpleDateFormat.parse(strDate));
}catch(ParseException e){
e.printStackTrace();
}
return (calendar.getTimeInMillis()+30000)/1000;
}
}
......@@ -37,11 +37,13 @@ public class TCPServer {
// client.start();
// }
// }
ServerSocket mainSocket ;
mainSocket = new ServerSocket(portNumber);
System.out.println("Start listening...");
while(true){
cmdJoin();
Socket clientSocket = null;
clientSocket = mainSocket.accept();
try{
......
/*
* 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 thealchemist;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author adwisatya
*/
public class Utility {
public long getTime(){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone utcZone = TimeZone.getTimeZone("UTC");
simpleDateFormat.setTimeZone(utcZone);
simpleDateFormat.setTimeZone(TimeZone.getDefault());
Date now = new Date();
Calendar calendar = Calendar.getInstance();
String strDate = simpleDateFormat.format(now);
try {
calendar.setTime(simpleDateFormat.parse(strDate));
}catch(ParseException e){
e.printStackTrace();
}
return (calendar.getTimeInMillis()+30000)/1000;
}
public String JSONtoString(String param, String JSON) throws JSONException{
JSONObject jsonObj = new JSONObject(JSON);
return jsonObj.getString(param);
}
public boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
// edited, to include @Arthur's comment
// e.g. in case JSONArray is valid as well...
try {
new JSONArray(test);
} catch (JSONException ex1) {
return false;
}
}
return true;
}
public String getIP(){
String addr = "";
try {
addr = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
return addr;
}
public String toMD5(String input) throws NoSuchAlgorithmException{
/* taken from http://www.mkyong.com/java/java-md5-hashing-example/ */
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment