Blame view

src/main/java/sourcecode/MockUp/MockUp.java 13.5 KB
f58f29ec   sumatek   add new project
1
2
3
4
package sourcecode.MockUp;

import java.io.IOException;
import java.io.OutputStream;
f58f29ec   sumatek   add new project
5
import java.net.InetSocketAddress;
886ed8a4   Supakit Jirasirichote   - config db host
6
import java.net.URLDecoder;
72eef90c   Sumate Kongpui   update mockup
7
8
9
import java.util.ArrayList;

import org.apache.commons.io.IOUtils;
f58f29ec   sumatek   add new project
10
import org.apache.http.Consts;
666338c1   Sumate Kongpui   update offset and...
11
import org.bson.Document;
5d7692c4   sumatek   update limit and ...
12
import org.json.JSONArray;
72eef90c   Sumate Kongpui   update mockup
13
import org.json.JSONObject;
f58f29ec   sumatek   add new project
14
15
16
17

import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
35ea4f23   sumatek   update get
18
import com.mongodb.MongoClientOptions;
f58f29ec   sumatek   add new project
19
20
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
35ea4f23   sumatek   update get
21
import com.mongodb.client.MongoCollection;
72eef90c   Sumate Kongpui   update mockup
22
import com.mongodb.client.MongoCursor;
f58f29ec   sumatek   add new project
23
24
25
26
27
28
29
30
31
32
33
34
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";
f58f29ec   sumatek   add new project
35
36
	private final static String DELETE = "DELETE";
	private static String DBNAME = "spw";
35ea4f23   sumatek   update get
37
	private static String DBHOST = "10.1.2.155:27017";
f58f29ec   sumatek   add new project
38
39
40
41
42
	
	public static void main(String[] args) throws Exception {
		
		int port = 6300;
		try {
72eef90c   Sumate Kongpui   update mockup
43
			if(args.length>0)
666338c1   Sumate Kongpui   update offset and...
44
45
				port = Integer.parseInt(args[0]);
			
72eef90c   Sumate Kongpui   update mockup
46
47
48
			if(args.length>1)
				DBNAME = args[1];
			
f58f29ec   sumatek   add new project
49
50
51
			if(args.length>2)
				DBHOST = args[2];
			
886ed8a4   Supakit Jirasirichote   - config db host
52
	        //connect mongo
f58f29ec   sumatek   add new project
53
54
55
			MongoConnector(DBNAME);	       
	        
			HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);	       
886ed8a4   Supakit Jirasirichote   - config db host
56
57
58
59
60
61
	        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();
72eef90c   Sumate Kongpui   update mockup
62
63
64
65
66
67
			System.out.println("Fail to run in port : "+port);
		}
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException{
f58f29ec   sumatek   add new project
68
        	String response = "";
886ed8a4   Supakit Jirasirichote   - config db host
69
        	try
f58f29ec   sumatek   add new project
70
71
72
73
74
75
        	{        	
	        	String method = t.getRequestMethod();        	
	        	String url = t.getRequestURI().toString();
	        	url = URLDecoder.decode(url, "UTF-8");
	        	
	//        	System.out.println(t.getRequestMethod());
886ed8a4   Supakit Jirasirichote   - config db host
76
	//        	if(!method.equals(GET))
f58f29ec   sumatek   add new project
77
78
79
80
81
82
	//        	{
	//	        	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(":");
72eef90c   Sumate Kongpui   update mockup
83
84
85
	//	//        	System.out.println(b[0]);
	//	        	String c = b[0].replace("{", "").trim().replace("\"", "");
	//	//        	System.out.println(c);
35ea4f23   sumatek   update get
86
	//	        	keyBody = (String) body.get(c);
f58f29ec   sumatek   add new project
87
	//        	}
35ea4f23   sumatek   update get
88
89
90
91
92
	//        	System.out.println(body.get(c));
	        	
	//        	for(Entry<String, List<String>> row:t.getRequestHeaders().entrySet())
	//        	{
	//        		System.out.println(row.getKey());
5d7692c4   sumatek   update limit and ...
93
94
95
96
97
98
99
100
101
102
103
104
105
106
	//        		System.out.println(row.getValue());
	//        	}
	//        	System.out.println(t.getRequestHeaders());
	//        	System.out.println(t.getRequestURI());
	          
	        	
	        	String keyData = findKey(method,url,IOUtils.toString(t.getRequestBody(),Consts.UTF_8));
	        	
	        	String collectionName = getSuffixTableName(url);     	
	        	JSONObject responsJSON = new JSONObject();
	        	
	        	//find retry
	        	
	        	ArrayList<String> retryList = findRetry(method,keyData);
666338c1   Sumate Kongpui   update offset and...
107
108
109
110
111
112
113
114
115
116
117
118
	        	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");
5d7692c4   sumatek   update limit and ...
119
120
121
122
123
124
	        			responsJSON.put("resultCode", "50000");
			    		responsJSON.put("resultDescription", "Retry");
	        		}
	        		
	            	BasicDBObject find = new BasicDBObject();
	            	find.put("key", rowJSON.get("key"));
35ea4f23   sumatek   update get
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
	//            	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<String> responseList = getDBData(keyData,collectionName,method);      	

		        	
		        	
		        	if(responseList.size() == 0)
		        	{
		        		System.out.println("not any Data");
		        		responsJSON.put("resultCode", "80000");
5d7692c4   sumatek   update limit and ...
150
			    		responsJSON.put("resultDescription", "MockUp error : No data in "+method.toLowerCase()+"_"+collectionName+"!!!");
35ea4f23   sumatek   update get
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
		        	}else
		        	{
		        		if(method.equals(GET) && responseList.size() > 1)
			    		{
		        			ArrayList<Object> resultData = new ArrayList<Object>();		    		
				        	for(int i=0;i<responseList.size();i++)
				        	{
				        		JSONObject rowJSON = new JSONObject(responseList.get(i));
				        		
				        		if(rowJSON.has("value"))
				        		{
				        			JSONObject value = (JSONObject) rowJSON.get("value");
				        			if(value.has("resultData"))
					        		{	
				        				
//				        				if((value.get("resultData").toString().length()> 0) && (value.get("resultData").toString().substring(0,1).equals("[")))
//				        				{
////				        					Object test = gson.fromJson(value.get("resultData").toString(), Object.class);
////				        					System.out.println(test);
//				        					
////				        					value.get("resultData").toString()
//				        					JSONObject resultlist = new JSONObject("{'test' : "+value.get("resultData").toString()+"}");
////				        					System.out.println(resultlist.get("test"));
//				        					JSONArray JSONArrayData = value.getJSONArray("resultData");
//				        					System.out.println("aaaaaaaaaaaaaaaaaaaa"+JSONArrayData.get(0));
////				        					for(int n=0;n<resultlist.getJSONObject("test").length();n++)
////				        					{
//////				        						System.out.println(resultlist.get());
////				        					}
////				        					System.out.println(resultlist.get("test"));
////				        					System.out.println("{'test' : "+value.get("resultData").toString()+"}");
//				        				}
				        				
				        				try{
				        					JSONArray JSONArrayData = value.getJSONArray("resultData");
//				        					System.out.println("bbbbbbbbbb"+JSONArrayData.length());
				        					for(int n=0;n<JSONArrayData.length();n++)
				        					{
				        						resultData.add(JSONArrayData.get(n));
//				        						System.out.println(JSONArrayData.get(n));
f58f29ec   sumatek   add new project
191
				        					}
35ea4f23   sumatek   update get
192
				        				}catch(Exception e)
5d7692c4   sumatek   update limit and ...
193
				        				{				
35ea4f23   sumatek   update get
194
195
196
197
198
199
200
201
202
203
204
205
//				        					e.printStackTrace();
				        					resultData.add(value.get("resultData"));
				        				}
				        				
					        		}
				        		}
				        		
		            		}
				        	
				        	responsJSON.put("resultCode", "20000");
				    		responsJSON.put("resultDescription", "Success");
				    		responsJSON.put("resultData",resultData);
5d7692c4   sumatek   update limit and ...
206
				    		responsJSON.put("rowCount",resultData.size());
35ea4f23   sumatek   update get
207
208
209
210
211
212
213
214
215
216
		        			
			    		}else
			    		{
			    			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");
35ea4f23   sumatek   update get
217
218
					    		responsJSON.put("resultDescription", "Success");
			    			}
35ea4f23   sumatek   update get
219
			    		}
35ea4f23   sumatek   update get
220
		        	}
5d7692c4   sumatek   update limit and ...
221
		        	
35ea4f23   sumatek   update get
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
		        	///////////////////////////////////////////////////////////////////////////////////////////////////////////////		        	
		        	

	        	}
	        	
	        	
	        	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());
	    			
5d7692c4   sumatek   update limit and ...
240
	    		}
35ea4f23   sumatek   update get
241
242
243
244
245
246
247
248
249
        	
        	t.getResponseHeaders().set("Content-Type", "application/json");
        	t.sendResponseHeaders(200, response.length());
        	OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
    
72eef90c   Sumate Kongpui   update mockup
250
251
252
253
254
255
256
257
258
259
    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;
		    }
35ea4f23   sumatek   update get
260
261
262
263
264
265
266
267
		}
		return value;
	}

   
    private static void MongoConnector(String db) {
    	
    	String username = "";
5d7692c4   sumatek   update limit and ...
268
		String password = "";
666338c1   Sumate Kongpui   update offset and...
269
270
271
272
		String address = DBHOST;
		String dbname = db;
		String authSource = db;
		int timeoutMongoDB = 10000;		
5d7692c4   sumatek   update limit and ...
273
274
275
276
277
		
		 MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder(); 
			optionsBuilder.connectTimeout(timeoutMongoDB); 
			optionsBuilder.socketTimeout(timeoutMongoDB); 
			optionsBuilder.serverSelectionTimeout(timeoutMongoDB);
35ea4f23   sumatek   update get
278
279
280
281
282
283
284
285
286
287
288
289
290
291

//			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<String> collectionNames = database.listCollectionNames().iterator();
			System.out.println("MongoDB Connect to "+uri.toString()+" Success");
72eef90c   Sumate Kongpui   update mockup
292
293
294
295
296
297
298
299
300
			System.out.println("MongoDB Collections in datebase");
			while (collectionNames.hasNext()) {
				String collectionName = collectionNames.next();
				System.out.println(" |_ "+collectionName);		
				
			}
    }
    
    private static ArrayList<String> getDBData(String keyData,String collectionName,String method)
f58f29ec   sumatek   add new project
301
    {
72eef90c   Sumate Kongpui   update mockup
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329

    	ArrayList<String> returnData = new ArrayList<String>();
    	collectionName = method.toLowerCase()+"_"+collectionName;
    	System.out.println("===> Find Normal");
    	BasicDBObject basicDBObject = new BasicDBObject();
    	basicDBObject.put("key", keyData);
    	returnData = getDB(basicDBObject,collectionName);
    	
    	if(returnData.size() == 0)
    	{
    		System.out.println("===> Go to Main flow");
    		BasicDBObject basicDBObject2 = new BasicDBObject();
        	basicDBObject2.put("key", "");
    		returnData = getDB(basicDBObject2,collectionName);
    	}    	
    	
    	

    	
    	
    	return returnData;
    }

    private static String findKey(String method,String url,String bodyData)
    {
    	String returnData = "";
    	
    	switch (method) {
f58f29ec   sumatek   add new project
330
331
		case GET:
		case DELETE:
886ed8a4   Supakit Jirasirichote   - config db host
332
333
334
335
336
337
338
339
340
341
342
343
			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:
72eef90c   Sumate Kongpui   update mockup
344
345
346
347
348
349
350
351
			break;
		}
    	
    	return returnData;
    }
    
    private static ArrayList<String> findRetry(String method,String keyData)
    {
886ed8a4   Supakit Jirasirichote   - config db host
352
353
    	ArrayList<String> returnData = new ArrayList<String>();
    	
f58f29ec   sumatek   add new project
354
355
356
    	System.out.println("===>Find retry");
    	BasicDBObject basicDBObject = new BasicDBObject();
    	basicDBObject.put("key", keyData);
72eef90c   Sumate Kongpui   update mockup
357
358
    	String collectionName = method.toLowerCase()+"_retry";
    	returnData = getDB(basicDBObject,collectionName);
886ed8a4   Supakit Jirasirichote   - config db host
359
    	
f58f29ec   sumatek   add new project
360
    	if(returnData.size() == 0)
72eef90c   Sumate Kongpui   update mockup
361
    	{
f58f29ec   sumatek   add new project
362
363
364
365
366
367
368
369
370
    		BasicDBObject basicDBObject2 = new BasicDBObject();
        	basicDBObject2.put("key", "");
    		returnData = getDB(basicDBObject2,collectionName);
    	}    	
    	
    	
    	return returnData;    	
    }
    
72eef90c   Sumate Kongpui   update mockup
371
    private static ArrayList<String> getDB(BasicDBObject basicDBObject,String collectionName)
f58f29ec   sumatek   add new project
372
373
374
375
    {
    	ArrayList<String> returnData = new ArrayList<String>();
    	
    	System.out.println("CollectionName : " + collectionName);
886ed8a4   Supakit Jirasirichote   - config db host
376
    	System.out.println("Find : "+basicDBObject.toJson());
f58f29ec   sumatek   add new project
377
378
379
380
381
382
383
384
385
386
387
388
389
    	
    	MongoCollection<Document> collection = database.getCollection(collectionName);
    	FindIterable<Document> findData = collection.find(basicDBObject);
    	MongoCursor<Document> 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;
5d7692c4   sumatek   update limit and ...
390
    	
f58f29ec   sumatek   add new project
391
    }
35ea4f23   sumatek   update get
392
    
f58f29ec   sumatek   add new project
393
    private static void setDB(BasicDBObject find,Document doc,String collectionName)
5d7692c4   sumatek   update limit and ...
394
    {
35ea4f23   sumatek   update get
395
396
//    	System.out.println("Start Update Mongo");

72eef90c   Sumate Kongpui   update mockup
397
    	MongoCollection<Document> collection = database.getCollection(collectionName);
35ea4f23   sumatek   update get
398
    	Document updateDoc = collection.findOneAndReplace(find, doc);		
5d7692c4   sumatek   update limit and ...
399
		
f58f29ec   sumatek   add new project
400
    	System.out.println("Update Mongo");
35ea4f23   sumatek   update get
401
402
403
    }
    
}
5d7692c4   sumatek   update limit and ...

35ea4f23   sumatek   update get

f58f29ec   sumatek   add new project

35ea4f23   sumatek   update get

f58f29ec   sumatek   add new project

35ea4f23   sumatek   update get

f58f29ec   sumatek   add new project

72eef90c   Sumate Kongpui   update mockup

35ea4f23   sumatek   update get

f58f29ec   sumatek   add new project

f58f29ec   sumatek   add new project

35ea4f23   sumatek   update get

72eef90c   Sumate Kongpui   update mockup

35ea4f23   sumatek   update get

5d7692c4   sumatek   update limit and ...

666338c1   Sumate Kongpui   update offset and...

5d7692c4   sumatek   update limit and ...

666338c1   Sumate Kongpui   update offset and...

f58f29ec   sumatek   add new project