package com.glodon.com.test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Manager {
	//缓存消息队列
	private static LinkedList<String> list = new LinkedList<String>();
	
	/*
	 * 发送方法
	 * 返回true:成功发送	  
	 * 返回false:网络问题发送失败会有断网续传机制将数据先写到缓存
	 * 抛出异常:发送的json格式不对或字段没有符合埋点规范
	 */
	public static boolean sendToServer(String jsonString) throws Exception{
		/*//先看本地文件是否存在,存在先发
		File directory = new File("");
		String path = directory.getAbsolutePath();
		System.out.println(path);
		File file = new File(path + "\\data.txt");
		if(file.exists() && file.length() > 0){
			readFromFileToList(file);//本地文件内容读到list中
			//解密
			for(int i = 0; i < list.size(); i ++) list.set(i,new String(decode(list.get(i))));
		}
		if(!list.isEmpty()){
			JSONArray arr = JSONArray.fromObject(list);
			//添加用于标记存盘后发送的tag
			String tag = "{'pcode':'-101000','fncode':'111','trigertime':'1970/01/01 00:00:00 000','tag':''}";
			JSONObject jo = JSONObject.fromObject(tag);
			arr.add(jo);
			//发送服务器地址
			String url = "http://tj.glodon.com/applog2/LogAccept";
	        boolean flag = true;
	        try{
	        	sendPost(url, compress(arr.toString()));
	        }catch(Exception e){
	        	flag = false;
	        	System.out.println("批量发送失败");
	        }
	        if(flag) list.clear();
		}*/
		
		return sendJsonObject(jsonString);
	}
	
	private static boolean sendJsonObject(String jsonString) throws Exception{
		
		//先对json串进行简单校验
		JSONObject jo = JSONObject.fromObject(jsonString);  
	//	format(jo);
        
        //将单个jsonString封装成JSONArray并进行gzip压缩
        byte[] arr = compress("[" + jo.toString() + "]");
        
        //发送数据
//        String url = "http://tj.glodon.com/applog2";
//        String url = "http://localhost:8088/LogAccept";
        String url = "http://io.glodon.com/test_logs/LogAccept";
//        String url = "http://tj.glodon.com/applog2/LogAccept";
//        String url = "http://10.127.49.98:8088/web_log";
        boolean res = true;
        try{
        	sendPost(url, arr);
//        	sendGet(url, arr);
        }catch(Exception e){
        	//在此扩展断网续传机制
        	System.out.println(e);
    		if(list.size() > 1000){
    			list.removeFirst();
    			list.add(jo.toString());
    		}else{
    			list.add(jo.toString());
    		}
        	res = false;
        }
        
		return res;
	}
	
	//程序退出时将list数据写入本地
	private static void writeToFile(File file){
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//加密
		for(int i = 0; i < list.size(); i ++) list.set(i, encode(list.get(i).getBytes()));
		
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(list);
			list.clear();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	private static void readFromFileToList(File file) {
		// 将文件数据读入缓存list
		if (!file.exists() || file.length() == 0) {
			return;
		}
		System.out.println("读文件");
		FileInputStream freader = null;
		ObjectInputStream objectInputStream = null;
		try {
			freader = new FileInputStream(file);
			objectInputStream = new ObjectInputStream(freader);
			LinkedList<String> list2 = (LinkedList<String>) objectInputStream.readObject();
			list.addAll(list2);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(objectInputStream != null){
				try {
					objectInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(freader != null){
				try {
					freader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		System.gc();    //加上确保文件能删除,不然可能删不掉  
		System.out.println("删除文件" + file.delete());
	}
	
	//简单校验
	private static void format(JSONObject jo) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss SSS");
		if(!jo.containsKey("pcode") ||!(jo.getString("pcode").equals("-103000") || jo.getString("pcode").equals("-103001"))
				|| !jo.containsKey("fncode")|| !jo.containsKey("trigertime")){
			throw new Exception("the necessary key is not contain");
		}
		if(!jo.containsKey("sys") & !jo.getString("pcode").equals("-103000")){
			throw new Exception("json key is not standard");
		}
		if(jo.containsKey("sys") && ("1".equals(jo.getString("sys")) || "2".equals(jo.getString("sys")))){
			if(!jo.getString("pcode").equals("-103001")) {
				throw new Exception("json key is not standard");
			}
		}
		sdf.parse(jo.getString("trigertime"));
	}

	
	/** 
     * 字符串压缩为GZIP字节数组 
     *  
     * @param str 
     * @return
     */  
    public static byte[] compress(String str) {  
        if (str == null || str.length() == 0) {  
            return null;  
        }  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        GZIPOutputStream gzip = null;  
        byte[] compressed;
        try {  
            gzip = new GZIPOutputStream(out);  
            gzip.write(str.getBytes());  //"utf-8"
            gzip.close();  
            compressed = out.toByteArray();
        } catch (IOException e) {  
        	compressed = null;
        }finally{
        	if(gzip != null){
        		try {
					gzip.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        	if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
        }
        return compressed;  
    }  
	

	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @return 所代表远程资源的响应结果
	 * @throws Exception 
     */
    private static String sendPost(String url, byte[] arr) throws Exception {
    	OutputStream out = null;
        BufferedReader in = null;
        ByteArrayOutputStream bos = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = conn.getOutputStream();
            // 发送请求参数
            out.write(arr);
            // flush输出流的缓冲
            out.flush(); 
            
            //接收返回值
            InputStream is = null;
            if(conn.getResponseCode() == HttpURLConnection.HTTP_OK || conn.getResponseCode() == HttpURLConnection.HTTP_CREATED
            		|| conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED)
            	is = conn.getInputStream();
            else{
            	is = conn.getErrorStream();
            	throw new Exception("request is not deal correct!");
            }
          byte[] buf = new byte[1024];
          bos = new ByteArrayOutputStream();
          int offset = -1;
          while((offset = is.read(buf)) != -1){
        	  bos.write(buf, 0, offset);
          }
          System.out.println(bos.toString());
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            throw e;
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
                if(bos != null){
                	bos.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }



	/**
	 * 向指定 URL 发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的 URL
	 * @return 所代表远程资源的响应结果
	 * @throws Exception
	 */
	private static String sendGet(String url, byte[] arr) throws Exception {
		OutputStream out = null;
		BufferedReader in = null;
		ByteArrayOutputStream bos = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			// 获取URLConnection对象对应的输出流
			out = conn.getOutputStream();
			// 发送请求参数
			out.write(arr);
			// flush输出流的缓冲
			out.flush();

			//接收返回值
			InputStream is = null;
			if(conn.getResponseCode() == HttpURLConnection.HTTP_OK || conn.getResponseCode() == HttpURLConnection.HTTP_CREATED
					|| conn.getResponseCode() == HttpURLConnection.HTTP_ACCEPTED)
				is = conn.getInputStream();
			else{
				is = conn.getErrorStream();
				throw new Exception("request is not deal correct!");
			}
			byte[] buf = new byte[1024];
			bos = new ByteArrayOutputStream();
			int offset = -1;
			while((offset = is.read(buf)) != -1){
				bos.write(buf, 0, offset);
			}
			System.out.println(bos.toString());
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!"+e);
			throw e;
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
				if(bos != null){
					bos.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}





	//加密
	   private static String encode(byte[] bstr){    
	   return new sun.misc.BASE64Encoder().encode(bstr);    
	   }    
	   
	   //解密
	   private static byte[] decode(String str){    
	   byte[] bt = null;    
	   try {    
	       sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();    
	       bt = decoder.decodeBuffer( str );    
	   } catch (IOException e) {    
	       e.printStackTrace();    
	   }    
	       return bt;    
	   }    
	
	public static void main(String[] args){
		//String jsonString = "[{\"id\":\"1\",\"name\":\"zhangsan\",\"query\":\"{\'a\':\'b\'}\"},{\"id\":\"2\",\"name\":\"lisi\",\"age\":14,\"mm\":\"nn\"}]";
		for(int i = 0; i < 2; i ++){
			String jsonString = "{\"ak\":\"ak\",\"vername\":\"bim web云测试\",\"mac\":\"C3BBAD16-B47F-4DBB-944F-13500C604648\",\"prjname\":\"大小写测试.GBQ5\",\"fncode\":1021,\"query\":{\"inforegion\":\"北京\"},\"fnname\":\"点击造价\",\"hardwareid\":\"C3BBAD16-B47F-4DBB-944F-13500C604648\",\"trigertime\":\"2017/04/12 16:40:11 594\",\"sys\":2,\"ver\":\"1.1.1\",\"projectid\":\"ff8080815b5b68f8015b6023d29e08a6\",\"sysver\":\"10.3\",\"pcode\":\"-103000\",\"utype\":\"2\",\"fngroup\":\"造价页签\",\"gid\":\"6127630218902238065\",\"receivetime\":\"2017/04/12 16:40:07 858\",\"ip\":\"223.104.3.238\"}";
//			String jsonString = "http://10.127.49.96:8088/web_event/web.gif?method=web_event_srv.upload&event={\"ut\": \"2018-10-24 15:43:27\",\"tz\": 28800000,\"debug\": 0,\"ak\": \"fe7d85c77a704c53ad0e88dd08444cbe\",\"usr\": {\"did\": \"16699fce3892d-01f75659aebb9d-5c1b3517-1fa400-16699fce38a156\"},\"data\": [\n" +
//					"{\"dt\": \"evt\",\"pr\": {\"$ct\": 1540367007080,\"$tz\": 28800000,\"$sid\": 1540365706836,\"$url\": \"http://10.127.49.96:8088/zhuge/zhugeanalyticstest.html\",\"$ref\": \"\",\"$referrer_domain\": \"\",\"$eid\": \"fncode\",\"_pcode\": 1,\"_sessionid\": 1540365706836,\"_fncode\": \"fncode\",\"_fnname\": \"fnname\",\"_fngroup\": \"fngroup\",\"_trigertime\": \"\",\"_device_id\": \"16699fce3892d-01f75659aebb9d-5c1b3517-1fa400-16699fce38a156\",\"_query\": {\"a\": 1,\"b\": \"sadf\",\"v\": {\"a\": 12}},\"_appname\": \"whqtest\"}}\n" +
//					"]}&_=1540367007081";
			try {
				System.out.println(Manager.sendToServer(jsonString));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
//		for(int i = 0; i < 1; i ++){
//			String jsonString = "{\"vername\":\"云计价助手\",\"mac\":\"C3BBAD16-B47F-4DBB-944F-13500C604648\",\"prjname\":\"大小写测试.GBQ5\",\"fncode\":1021,\"query\":{\"inforegion\":\"北京\"},\"fnname\":\"点击造价\",\"hardwareid\":\"C3BBAD16-B47F-4DBB-944F-13500C604648\",\"trigertime\":\"2017/04/12 16:40:11 594\",\"sys\":2,\"ver\":\"1.1.1\",\"projectid\":\"ff8080815b5b68f8015b6023d29e08a6\",\"sysver\":\"10.3\",\"pcode\":\"-101002\",\"utype\":\"2\",\"fngroup\":\"造价页签\",\"gid\":\"6127630218902238065\",\"receivetime\":\"2017/04/12 16:40:07 858\",\"ip\":\"223.104.3.238\"}";
//			try {
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			System.out.println("--------------");
//		}
//		
//		System.out.println("****************万恶的分割线******************");
//		try {
//			Thread.sleep(10 * 1000);
//		} catch (InterruptedException e1) {
//			e1.printStackTrace();
//		}
		
//		for(int i = 0; i < 1; i ++){
//			String jsonString = "{\"pcode\":\"-101002\",\"fncode\":111000,\"trigertime\":\"2016/11/30 15:20:45 52\",\"mac\":\"122\",\"sys\":2,\"sysver\":\"mm\",\"query\":\"{\'ppp\':\'qqq\',\'哈哈\':\'呵呵\'}\"}";
//			try {
//				System.out.println(Manager.sendToServer(jsonString));
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			System.out.println("--------------");
//		}
		
		File directory = new File("");
		String path = directory.getAbsolutePath();
		System.out.println(path);
		File file = new File(path + "\\data.txt");
		writeToFile(file);
	}
	
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
150
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
Last Updated: 11/5/2020, 2:10:08 AM
  • 在线客服

  • 意见反馈