whyclj
2020-10-20 2a1aa055a75826211327ce37a7ad761bb7016c68
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package com.dev.data;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
 
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import com.base.Com;
import com.config.AppConfig;
 
/**
 *     ¶ÁÈ¡ÅäÖÃÎļþ
 * @author LiJun
 *
 */
public class ReadConfigFile {
    //±¾µØÅäÖÃÎļþĿ¼[ΪÁ˽â¾ö¿Í»§¶ËÆô¶¯Ê±²»ÄÜÁ¬½Óµ½ftp·þÎñÆ÷ʱbug]
    public static String cfgpath = System.getProperty("user.dir") + File.separator + "config/RealList.txt";
    
    //ϵͳÀàÐÍ
    public static final int ZIZHAN_SYS_TYPE = 1;
    public static final int ZHONGDUAN_SYS_TYPE = 2;
    
    
    private static String FileRoot = "/config/";                //Êý¾Ý¸ùĿ¼
    public String battName = "";
    public FTPClient ftp;
    public String filename = "RealList.txt";
    public String server_ip = "192.168.7.130";        //É豸ipµØÖ·
    public String userNmae  = "ftp";                //ĬÈÏftpÓû§Ãû
    public String passWord  = "";                    //ĬÈÏÓû§ÃÜÂë
    public int port = 21;                            //ĬÈ϶˿Ú
    public Map<Integer, String> sysTypes = new HashMap<Integer, String>(){ 
        { 
            put(ZIZHAN_SYS_TYPE,"×Óվϵͳ"); put(ZHONGDUAN_SYS_TYPE,"ÖÕ¶Ë");
        }
    };
    
    public ReadConfigFile() {
        
    } 
    
    public List readConfigData() {
        List configs = new ArrayList();
        boolean flag = false;
        try {
            System.out.println(cfgpath);
            if(ftpLogin(server_ip, port, userNmae, passWord)) {
                
                flag = true;
                judeFileExists(cfgpath);
                
                parseConfigFile(configs);
            }
            //System.err.println(configs.size());
            if(configs.size()<1){
                System.out.println("½âÎö±¾µØÅäÖÃÎļþ¡£¡£¡£");
                //µÇ½ftp·þÎñÆ÷ʧ°Ü,δ½âÎöµ½ÅäÖÃÎļþ,½âÎö±¾µØÎļþ
                parseLocalConfigFile(configs);
            }else {
                System.out.println("½âÎöÅäÖÃÎļþ³É¹¦"+configs.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //½âÎöÍê³ÉÍ˳öftpÁ¬½Ó
                disConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(flag) {
                System.out.println("µÇ½ftp·þÎñÆ÷³É¹¦ip:"+server_ip+";file:"+FileRoot+filename+";name:"+userNmae+";pass:"+passWord+";port:"+port+"; at "+Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));                
            }else {
                System.out.println("µÇ½ftp·þÎñÆ÷ʧ°Üip:"+server_ip+";file:"+FileRoot+filename+";name:"+userNmae+";pass:"+passWord+";port:"+port+"; at "+Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));                
            }
        }
        return configs;
    }
    
    /**
     *     ¶ÁÈ¡FTPÅäÖÃÎļþ
     * @param temp
     */
    public void parseConfigFile(List temp) {
        if (FileRoot.startsWith("/") && FileRoot.endsWith("/")) {
            //¸ü»»Ä¿Â¼µ½µ±Ç°Ä¿Â¼
            StringBuilder stringBuilder;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            BufferedReader bufferedReader = null;
            BufferedWriter bufferedWrite = null;
            try {
                this.ftp.changeWorkingDirectory(FileRoot);
                // ÐèÒª¼Ó´ËÅжϡ£·ñÔò£¬ftpĬÈϽ«¡®ÏîÄ¿ÎļþËùÔÚĿ¼֮ϵÄĿ¼£¨./£©¡¯Óë¡®ÏîÄ¿ÎļþËùÔÚĿ¼ÏòÉÏÒ»¼¶Ä¿Â¼ÏµÄĿ¼£¨../£©¡¯¶¼ÄÉÈëµÝ¹é£¬ÕâÑùÏÂÈ¥¾ÍÏÝÈëÒ»¸öËÀÑ­»·ÁË¡£Ð轫Æä¹ýÂ˵ô¡£
                inputStream = this.ftp.retrieveFileStream(filename);//¸ù¾ÝÖ¸¶¨Ãû³Æ»ñȡָ¶¨Îļþ
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
                outputStream = new FileOutputStream(new File(cfgpath));
                bufferedWrite = new BufferedWriter(new OutputStreamWriter(outputStream,"GBK"));
                String line=null;
                stringBuilder = new StringBuilder(150);
                int count = 0;
                while ((line = bufferedReader.readLine()) != null)
                {
                    bufferedWrite.write(line);
                    bufferedWrite.newLine();
                    bufferedWrite.flush();
                    stringBuilder.delete( 0, stringBuilder.length() );
                    stringBuilder.append(line);
                    readConfigTxt(stringBuilder,temp);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bufferedReader != null) {
                        bufferedReader.close();
                    }
                    if(inputStream != null) {
                        inputStream.close();
                    }
                    if(bufferedWrite != null) {
                        bufferedWrite.close();
                    }
                    if(outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        }
    }
    
    /**
     *     ¶ÁÈ¡±¾µØÅäÖÃÎļþ
     * @param temp
     */
    public void parseLocalConfigFile(List temp) {
        File file = new File(cfgpath);
        System.out.println(cfgpath);
        if (file.exists()) {
            //¸ü»»Ä¿Â¼µ½µ±Ç°Ä¿Â¼
            StringBuilder stringBuilder;
            InputStream inputStream = null;
            BufferedReader bufferedReader = null;
            try {
                // ÐèÒª¼Ó´ËÅжϡ£·ñÔò£¬ftpĬÈϽ«¡®ÏîÄ¿ÎļþËùÔÚĿ¼֮ϵÄĿ¼£¨./£©¡¯Óë¡®ÏîÄ¿ÎļþËùÔÚĿ¼ÏòÉÏÒ»¼¶Ä¿Â¼ÏµÄĿ¼£¨../£©¡¯¶¼ÄÉÈëµÝ¹é£¬ÕâÑùÏÂÈ¥¾ÍÏÝÈëÒ»¸öËÀÑ­»·ÁË¡£Ð轫Æä¹ýÂ˵ô¡£
                inputStream = new FileInputStream(file);//¸ù¾ÝÖ¸¶¨Ãû³Æ»ñȡָ¶¨Îļþ
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
                String line=null;
                stringBuilder = new StringBuilder(150);
                int count = 0;
                while ((line = bufferedReader.readLine()) != null)
                {
                    stringBuilder.delete( 0, stringBuilder.length() );
                    stringBuilder.append(line);
                    readConfigTxt(stringBuilder,temp);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bufferedReader != null) {
                        bufferedReader.close();
                    }
                    if(inputStream != null) {
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
 
        }
    }
    
    /**
     * ½âÎö×Ö·û´®ÖеÄÎļþÐÅÏ¢
     * @param str
     * @param devices
     */
    public void readConfigTxt(StringBuilder str,List devices) {
        if(null != str) {
             /* ÕÒ³öÖ¸¶¨µÄ2¸ö×Ö·ûÔÚ ¸Ã×Ö·û´®ÀïÃæµÄ Î»Öà*/
            int StartIndex = str.indexOf("@");
            int EndIndex = str.lastIndexOf("$");
            if(StartIndex >= 0 && EndIndex >=0 && str.length() > 18) {
                String[] s = str.substring(StartIndex+1,EndIndex).split(",");
                ConfigData temp = new ConfigData();
                temp.dev_number = Integer.parseInt(s[0].trim());    //Êý¾Ý±àºÅ
                temp.data_value = s[1].trim();                        //Êý¾ÝÃû³Æ
                temp.unit = s[2].trim();                            //µ¥Î»
                temp.value_min = Float.parseFloat(s[3]);            //×îСֵ
                temp.value_max = Float.parseFloat(s[4]);            //×î´óÖµ
                temp.dataacc = Float.parseFloat(s[5]);                //¾«¶È(1->ÕûÊý£»10->0.1;100->0.01)
                temp.alm_num1 = Integer.parseInt(s[6].trim());        //±¨¾¯1±àºÅ
                temp.alm_num1_value = Float.parseFloat(s[7]);        //±¨¾¯1¸æ¾¯Öµ
                temp.alm_num2 = Integer.parseInt(s[8].trim());        //±¨¾¯2±àºÅ    
                temp.alm_num2_value = Float.parseFloat(s[9]);        //±¨¾¯2¸æ¾¯Öµ
                temp.varname = s[10].trim();                        //±äÁ¿Ãû³Æ
                //System.out.println(temp.dev_number+"====="+temp.varname);
                if(temp.varname.indexOf(":") >0) {
                    temp.vname = temp.varname.substring(0, temp.varname.indexOf(":"));                            //É豸±êʶ·û
                }
                temp.macsource = s[11].trim();                        //ʵʱÊý¾Ý¿âËù´¦¼ÆËã»ú
                temp.datasource = s[12].trim();                        //Êý¾ÝÔ´
                temp.dataaccess = s[13].trim();                        //»ñȡ;¾¶
                temp.vartype = Integer.parseInt(s[14].trim());        //±äÁ¿ÀàÐÍ(1¡ª>Ä£ÄâÁ¿;2->¿ª¹ØÁ¿;3->״̬Á¿)
                temp.wanlogo = s[15].trim();                        //ÒÔÌ«Íø±êʶ
                temp.frameposit = Integer.parseInt(s[16].trim());    //Ö¡ÖÐλÖÃ
                temp.defalutval = Float.parseFloat(s[17].trim());    //ĬÈÏÖµ
                temp.codename = s[18].trim();                        //´úºÅ
                devices.add(temp);
                //System.out.println(temp);
            }
        }
    }
    
    //·ÖÎöÅäÖÃÎļþÖеĽṹ
    public List<Device_inf> analyConfigFile(List<ConfigData> source,List<Device_inf> devices,List<ConfigData> cfgs) {
        //List<Device_inf> devices = new ArrayList<Device_inf>();
        boolean flag = false;
        int dev_id = 1001; 
        int sys_type = 1;
        System.out.println(source.size());
        for(int i = 0;i<source.size();i++) {
            flag = false;
            for(int j=0;j<devices.size();j++) {
                //×°Åä×ÓÕ¾Êý¾ÝÐÅÏ¢
                if(source.get(i).vname.equals(devices.get(j).dev_str) && devices.get(j).dev_id<2000){
                    flag = true;
                }
                
                
                //×°Åä×ÓÕ¾Êý¾Ý
                if("6".equals(source.get(i).wanlogo) && devices.get(j).dev_id/100 == 40) {
                    
                    //System.out.println(source.get(i).wanlogo+"===="+source.get(i).dev_number);
                    //1ºÅÆûÂÖ·¢µç»úÊý¾Ý
                    if(devices.get(j).dev_id%4000 == 1 && ((source.get(i).data_value.indexOf("1ºÅ")==0) ||(source.get(i).data_value.indexOf("1#")==0))) {
                        cfgs.add(source.get(i));
                        flag = true;
                    }
                    //2ºÅÆûÂÖ·¢µç»úÊý¾Ý
                    if(devices.get(j).dev_id%4000 == 2 && ((source.get(i).data_value.indexOf("2ºÅ")==0) ||(source.get(i).data_value.indexOf("2#")==0))) {
                        cfgs.add(source.get(i));
                        flag = true;
                    }
                }
                if(flag) {
                    if(source.get(i).vartype == Device_inf.ANALOG_DATATYPE) {
                        devices.get(j).addAnalog_count();
                    }else if(source.get(i).vartype == Device_inf.SWITCH_DATATYPE) {
                        devices.get(j).addSwitch_count();
                    }else if(source.get(i).vartype == Device_inf.STATE_DATATYPE) {
                        devices.get(j).addState_count();
                    }
                    devices.get(j).cfgdatas.add(source.get(i));
                    break;
                }
                
            }
            //ɸѡµôÖÕ¶ËÊý¾Ý
            if(!flag && !source.get(i).macsource.equals("ÖÕ¶Ë") && !source.get(i).macsource.contains("¿ØÖưå")) {                
                //System.err.println(i+"======" + source.get(i).vname+"==="+source.get(i).macsource+"==="+source.get(i).data_value);
                
                //еÄÉ豸ÐͺÅ
                Device_inf device = new Device_inf();
                device.dev_id = dev_id++;
                device.dev_name = source.get(i).macsource;        //É豸Ãû³Æ
                if(source.get(i).vname.contains("SN")) {
                    //×Óվϵͳ
                    device.sys_type = ZIZHAN_SYS_TYPE;
                    device.sys_name = sysTypes.get(ZIZHAN_SYS_TYPE); 
                }else if(source.get(i).vname.contains("0") || device.sys_name.equals("")) {
                    device.sys_type = ZHONGDUAN_SYS_TYPE;
                    device.sys_name = sysTypes.get(ZHONGDUAN_SYS_TYPE);
                }
                device.sys_ident= source.get(i).vname;            //ϵͳ±êʶ·û
                
                if(source.get(i).vartype == Device_inf.ANALOG_DATATYPE) {
                    device.addAnalog_count();
                }else if(source.get(i).vartype == Device_inf.SWITCH_DATATYPE) {
                    device.addSwitch_count();
                }else if(source.get(i).vartype == Device_inf.STATE_DATATYPE) {
                    device.addState_count();
                }
                device.cfgdatas.add(source.get(i));
                devices.add(device);
            }
        }
        return devices;
    }
    
    
    
    /**
     * ÖØÔع¹Ô캯Êý
     *
     * @param isPrintCommmand ÊÇ·ñ´òÓ¡ÓëFTPServerµÄ½»»¥ÃüÁî
     */
    public ReadConfigFile(AppConfig config) {
        server_ip = config.getEquie_device_ftp_ip();
        port = config.getEquie_device_ftp_port();
        userNmae = config.getEquie_device_ftp_username();
        passWord = config.getEquie_device_ftp_password();
        FileRoot = config.getEquie_device_ftp_file_path();
        
        ftp = new FTPClient();
    }
 
    /**
     *     µÇ½FTP·þÎñÆ÷
     *
     * @param host     FTPServer IPµØÖ·
     * @param port     FTPServer ¶Ë¿Ú
     * @param username FTPServer µÇ½Óû§Ãû
     * @param password FTPServer µÇ½ÃÜÂë
     * @return ÊÇ·ñµÇ¼³É¹¦
     * @throws IOException
     */
    public boolean login(String host, int port, String username, String password) throws IOException {
        try {
            this.ftp.connect(host, port);
            if (FTPReply.isPositiveCompletion(this.ftp.getReplyCode())) {
                if (this.ftp.login(username, password)) {
                    /**
                                        ÐèҪעÒâÕâ¾ä´úÂ룬Èç¹ûµ÷ÓÃList()·½·¨³öÏÖ£¬ÎļþµÄÎÞÏߵݹ飬ÓëÕæÊµÄ¿Â¼½á¹¹²»Ò»ÖµÄʱºò£¬¿ÉÄܾÍÊÇÒòΪתÂëºó£¬¶Á³öÀ´µÄÎļþ¼ÐÓëÕýʽÎļþ¼Ð×Ö·û±àÂë²»Ò»ÖÂËùµ¼Ö¡£
                                        ÔòÐèÈ¥µôתÂ룬¾¡¹ÜµÝ¹éÊdzöÏÖÂÒÂ룬µ«¶Á³öµÄÎļþ¾ÍÊÇÕæÊµµÄÎļþ£¬²»»áËÀµô¡£µÈ¶ÁÍêÖ®ºóÔÙ¸ù¾ÝÇé¿ö½øÐÐתÂë¡£
                                        Èç¹ûftp²¿ÊðÔÚwindowsÏ£¬Ôò£º
                         for (String arFile : f.arFiles) {
                             arFile = new String(arFile.getBytes("iso-8859-1"), "GBK");
                             logger.info(arFile);
                         }
                     */
                    ftp.enterLocalPassiveMode();        //ÉèÖóɱ»¶¯Ä£Ê½
                    this.ftp.setControlEncoding("utf-8");
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            if (this.ftp.isConnected()) {
//                this.ftp.disconnect();
//            }
        }
        return false;
    }
 
    /** 
     * @return ÅжÏÊÇ·ñµÇÈë³É¹¦ 
     * */  
    public boolean ftpLogin(String strIp,int intPorts,String username,String password) {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftp.setControlEncoding("GBK");
        this.ftp.configure(ftpClientConfig);
        try {
            if (intPorts > 0) {
                this.ftp.connect(strIp, intPorts);
            }else {
                this.ftp.connect(strIp);
            }
            // FTP·þÎñÆ÷Á¬½Ó»Ø´ð  
            int reply = this.ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftp.disconnect();
                return isLogin;
            }
            this.ftp.login(username, password);
            // ÉèÖô«ÊäЭÒé  
            this.ftp.enterLocalPassiveMode();
            this.ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            
            //System.out.println(this.ftpClient.getSystemType());
            // »ñÈ¡µÇ¼ÐÅÏ¢
            //FTPClientConfig config = new FTPClientConfig(this.ftpClient.getSystemType().split(" ")[0]);
            FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_OS2);
            config.setServerLanguageCode("zh");
            this.ftp.configure(config);
            // Ê¹Óñ»¶¯Ä£Ê½ÉèΪĬÈÏ
            //this.ftpClient.enterLocalPassiveMode();
            //System.out.println("999999999999999");
            isLogin = true;
        }catch (Exception e) {
            isLogin = false;
            e.printStackTrace();
        }
        //this.ftpClient.setBufferSize(1024 * 800);
        //this.ftpClient.setDataTimeout(120 * 1000);
        return isLogin;
    }
    
    /**
     * ¹Ø±ÕÊý¾ÝÁ´½Ó
     *
     * @throws IOException
     */
    public void disConnection() throws IOException {
        if (this.ftp.isConnected()) {
            this.ftp.disconnect();
        }
    }
    
    // ÅжÏÎļþÊÇ·ñ´æÔÚ
     public static void judeFileExists(String filepath) {
         File file = new File(filepath);
         if (file.exists()) {
             //ÎļþÒÑ´æÔÚ
         } else {
             //System.out.println("file not exists, create it ...");
             try {
                 File fileParent = file.getParentFile();
                 if(!fileParent.exists()){
                     fileParent.mkdirs();
                 }
                 file.createNewFile();
             } catch (IOException e) {
                // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         } 
     }
   
    public static void main(String[] args) {
        //ReadConfigFile util = new ReadConfigFile();
        
        //util.readBattTestData("Default_Battery","F2017-01-14 18.40.44.FBO");
        
 
        
    }
}