package sourcecode.MockUp; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import org.apache.commons.io.IOUtils; import org.apache.http.Consts; import org.bson.Document; import org.json.JSONArray; import org.json.JSONObject; import com.google.gson.Gson; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class MockUp { private static Gson gson = new Gson(); private static MongoDatabase database; private final static String GET = "GET"; private final static String POST = "POST"; private final static String PUT = "PUT"; private final static String DELETE = "DELETE"; private static String DBNAME = "spw"; private static String DBHOST = "10.1.2.155:27017"; public static void main(String[] args) throws Exception { int port = 6300; try { if(args.length>0) port = Integer.parseInt(args[0]); if(args.length>1) DBNAME = args[1]; if(args.length>2) DBHOST = args[2]; //connect mongo MongoConnector(DBNAME); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", new MyHandler()); server.setExecutor(null); // creates a default executor server.start(); System.out.println("Run in port : "+port); } catch(Exception e) { e.printStackTrace(); System.out.println("Fail to run in port : "+port); } } static class MyHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException{ String response = ""; try { String method = t.getRequestMethod(); String url = t.getRequestURI().toString(); url = URLDecoder.decode(url, "UTF-8"); String bodyData = IOUtils.toString(t.getRequestBody(),Consts.UTF_8); int limit = 0; if(!getKey("limit", url).equals("")) { try{ limit = Integer.parseInt(getKey("limit", url)); }catch(Exception e) { } } String[] fields = new String[0]; if(!getKey("fields", url).equals("")) fields = getKey("fields", url).split(","); // System.out.println(t.getRequestMethod()); // if(!method.equals(GET)) // { // String bodyData = IOUtils.toString(t.getRequestBody(),Consts.UTF_8); // JSONObject body = new JSONObject(bodyData); // String[] a = bodyData.split(","); // // System.out.println(a[0]); // String[] b = a[0].split(":"); // // System.out.println(b[0]); // String c = b[0].replace("{", "").trim().replace("\"", ""); // // System.out.println(c); // keyBody = (String) body.get(c); // } // System.out.println(body.get(c)); // for(Entry> row:t.getRequestHeaders().entrySet()) // { // System.out.println(row.getKey()); // System.out.println(row.getValue()); // } // System.out.println(t.getRequestHeaders()); // System.out.println(t.getRequestURI()); String keyData = findKey(method,url,bodyData); String collectionName = getSuffixTableName(url); JSONObject responsJSON = new JSONObject(); //find retry ArrayList retryList = findRetry(method,keyData); boolean notRetry = true; if(retryList.size() > 0) { JSONObject rowJSON = new JSONObject(retryList.get(0)); System.out.println("Count retry : "+rowJSON.get("count")); if(rowJSON.has("value")) responsJSON = (JSONObject) rowJSON.get("value"); else { System.out.println("not found vale or resultCode"); responsJSON.put("resultCode", "50000"); responsJSON.put("resultDescription", "Retry"); } BasicDBObject find = new BasicDBObject(); find.put("key", rowJSON.get("key")); // System.out.println(rowJSON.get("count")); int newCount = (int) rowJSON.get("count"); rowJSON.remove("count"); if(newCount > 0) { rowJSON.put("count", newCount-1); Document doc = Document.parse(rowJSON.toString()); setDB(find,doc,method.toLowerCase()+"_retry"); notRetry = false; } } if(notRetry) { ArrayList responseList = getDBData(keyData,collectionName,method,bodyData); if(responseList.size() == 0) { System.out.println("not any Data"); responsJSON.put("resultCode", "80000"); responsJSON.put("resultDescription", "MockUp error : No data in "+method.toLowerCase()+"_"+collectionName+"!!!"); }else { if(method.equals(GET) && responseList.size() > 1) { System.out.println("Multi Data => Merge"); ArrayList resultData = new ArrayList(); for(int i=0;i Direct"); JSONObject rowJSON = new JSONObject(responseList.get(0)); if(rowJSON.has("value")) responsJSON = (JSONObject) rowJSON.get("value"); else { System.out.println("not found vale or resultCode"); responsJSON.put("resultCode", "20000"); responsJSON.put("resultDescription", "Success"); } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////// } //limit responsJSON = limitData(responsJSON,limit); //field responsJSON = FieldsData(responsJSON,fields); response = responsJSON.toString(); System.out.println(""); System.out.println("URL : " + url); System.out.println("Method : " + method); System.out.println("Response : " + response); System.out.println(""); }catch(Exception e) { e.printStackTrace(); System.out.println("System error "+e.getMessage()); } t.getResponseHeaders().set("Content-Type", "application/json"); t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } } private static String getSuffixTableName(String url) { String value = null; String[] arrData = url.split("/"); for (String data : arrData) { if (data.contains(".json")) { int lastIndex = data.indexOf(".json"); value = data.substring(0, lastIndex); break; } } return value; } private static void MongoConnector(String db) { String username = ""; String password = ""; String address = DBHOST; String dbname = db; String authSource = db; int timeoutMongoDB = 10000; MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder(); optionsBuilder.connectTimeout(timeoutMongoDB); optionsBuilder.socketTimeout(timeoutMongoDB); optionsBuilder.serverSelectionTimeout(timeoutMongoDB); // optionsBuilder.connectionsPerHost(maxPoolSize); // optionsBuilder.minConnectionsPerHost(minPoolSize); MongoClientURI uri = new MongoClientURI("mongodb://"+username+":"+password+"@"+address+"/?authSource="+authSource, optionsBuilder); if(username.equals("")) uri = new MongoClientURI("mongodb://"+address+"/?authSource="+authSource, optionsBuilder); System.out.println("MongoDB Connecting to "+uri.toString()+"..."); @SuppressWarnings("resource") MongoClient mongoClient = new MongoClient(uri); database = mongoClient.getDatabase(dbname); //test connect and list collections MongoCursor collectionNames = database.listCollectionNames().iterator(); System.out.println("MongoDB Connect to "+uri.toString()+" Success"); System.out.println("MongoDB Collections in datebase"); while (collectionNames.hasNext()) { String collectionName = collectionNames.next(); System.out.println(" |_ "+collectionName); } } private static ArrayList getDBData(String keyData,String collectionName,String method,String bodyData) { ArrayList returnData = new ArrayList(); // collectionName = method.toLowerCase()+"_"+collectionName; System.out.println("===> Find Normal"); BasicDBObject basicDBObject = new BasicDBObject(); basicDBObject.put("key", keyData); returnData = getDB(basicDBObject,method.toLowerCase()+"_"+collectionName); if(returnData.size() == 0) { System.out.println("===> Go to Main flow"); BasicDBObject basicDBObject2 = new BasicDBObject(); basicDBObject2.put("key", ""); returnData = getDB(basicDBObject2,method.toLowerCase()+"_"+collectionName); // if(method.equals(POST) && returnData.size()>0) // { // //post main flow // JSONObject rowJSON = new JSONObject(returnData.get(0)); // rowJSON.remove("_id"); // JSONObject value = rowJSON.getJSONObject("value"); // value.put("resultData", new JSONObject(bodyData)); // // Document doc = Document.parse(rowJSON.toString()); // insertDB(doc,GET.toLowerCase()+"_"+collectionName); // } } return returnData; } private static String findKey(String method,String url,String bodyData) { String returnData = ""; switch (method) { case GET: case DELETE: returnData = url; break; case POST: case PUT: JSONObject body = new JSONObject(bodyData); String[] a = bodyData.split(","); String[] b = a[0].split(":"); String c = b[0].replace("{", "").trim().replace("\"", ""); returnData = (String) body.get(c); break; default: break; } return returnData; } private static ArrayList findRetry(String method,String keyData) { ArrayList returnData = new ArrayList(); System.out.println("===>Find retry"); BasicDBObject basicDBObject = new BasicDBObject(); basicDBObject.put("key", keyData); String collectionName = method.toLowerCase()+"_retry"; returnData = getDB(basicDBObject,collectionName); if(returnData.size() == 0) { BasicDBObject basicDBObject2 = new BasicDBObject(); basicDBObject2.put("key", ""); returnData = getDB(basicDBObject2,collectionName); } return returnData; } private static ArrayList getDB(BasicDBObject basicDBObject,String collectionName) { ArrayList returnData = new ArrayList(); System.out.println("CollectionName : " + collectionName); System.out.println("Find : "+basicDBObject.toJson()); MongoCollection collection = database.getCollection(collectionName); FindIterable findData = collection.find(basicDBObject); MongoCursor cursor = findData.iterator(); while(cursor.hasNext()){ Document rawRow = cursor.next(); System.out.println("found retry _id : "+rawRow.get("_id")); // System.out.println("count : "+rawRow.get("count")); returnData.add(rawRow.toJson()); } return returnData; } private static void setDB(BasicDBObject find,Document doc,String collectionName) { // System.out.println("Start Update Mongo"); MongoCollection collection = database.getCollection(collectionName); Document updateDoc = collection.findOneAndReplace(find, doc); System.out.println("Update Mongo"); } private static void insertDB(Document doc,String collectionName) { // System.out.println("Start Update Mongo"); MongoCollection collection = database.getCollection(collectionName); collection.insertOne(doc); System.out.println("Insert Mongo"); } private static JSONObject limitData(JSONObject responsJSON,int limit) { if(limit != 0) { int size = 0; try{ System.out.println("Limit : "+limit); JSONArray JSONArrayData = responsJSON.getJSONArray("resultData"); ArrayList limitResultData = new ArrayList(); size = JSONArrayData.length(); for(int i=0;i 0 && responsJSON.has("resultData")) { String select = ""; for(String row:fileds) select += ","+row; System.out.println("Select Fields => "+select.substring(1)); try{ JSONArray jsonArray = responsJSON.getJSONArray("resultData"); JSONArray newJsonArray = new JSONArray(); for(int i=0;i 0) { JSONObject newResponse = new JSONObject(); for(String row:fileds) { if(json.has(row)) newResponse.put(row, json.get(row)); } returnData = newResponse; }else { returnData = json; } return returnData; } public static ArrayList getKeyUrl(String url) { ArrayList arrData = new ArrayList(); String[] arr = url.split("[/]"); for(int i = 0; i < arr.length; i++) { if(arr[i].contains("?")) arr[i] = arr[i].substring(0, arr[i].indexOf("?")); if(!arr[i].equals("")) arrData.add(arr[i]); } return arrData; } public static HashMap> getKeyFilter(String url) { String key = "filter="; String value = null; HashMap> hashMap = new HashMap>(); value = url.substring(url.indexOf(key)+key.length()); value = value.substring(0, value.indexOf(")&")+1); String[] array = value.split("[()]"); for(int i = 0; i < array.length; i++) { String[] temp = array[i].split("="); if(temp.length > 1) { // System.out.println(temp[0]+" "+temp[1]); if(hashMap.containsKey(temp[0])) { hashMap.get(temp[0]).add(temp[1]); } else { ArrayList tempArr = new ArrayList<>(); tempArr.add(temp[1]); hashMap.put(temp[0], tempArr); } } } return hashMap; } public static String getKey(String key, String url) { key = key + "="; String value = ""; if(url.contains(key)) { value = url.substring(url.indexOf(key)+key.length()); if(value.indexOf("&") != -1) value = value.substring(0, value.indexOf("&")); } return value; } }