a
554325746@qq.com
2020-01-15 956063ff14bc75e3a2a97c7bcaa06b9edc84ad24
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
package com.basic.security.manager;
 
import android.database.Cursor;
import android.database.SQLException;
import android.text.TextUtils;
 
import com.basic.security.model.ModelAdapter;
import com.basic.security.model.Person;
import com.basic.security.model.Sync;
import com.basic.security.utils.Base64Util;
import com.basic.security.utils.Constants;
import com.basic.security.utils.ExceptionUtil;
import com.basic.security.utils.FrameUtil;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
 
public class BaseManager {
    public static Map<String, List<String>> tableColumnNames = new HashMap<>();
    public static Set<String> syncTableNames = new HashSet<>();
 
    static {
        syncTableNames.addAll(Arrays.asList(
                "org",
                "person",
                "time",
                "person_identity",
                "dbtablepersons",
                "dbTables",
                "visit"
        ));
    }
 
    public static void save(ModelAdapter modelAdapter) {
        String insertSql = "";
        try {
            if (modelAdapter != null) {
                String table = modelAdapter.getString(Constants.TABLE);
                if (table == null) {
                    table = "";
                }
                PersonCameraImagePathManager.updateCameraImagePathExist(modelAdapter);
                GetInsertOrUpdateSql getInsertOrUpdateSql = new GetInsertOrUpdateSql(modelAdapter).invoke();
                insertSql = getInsertOrUpdateSql.getInsertSql();
                if (
                        syncTableNames.contains(table) &&
                                !Constants.FALSE.equals(modelAdapter.getString(Sync.needSync))) {
                    if (table.equals("person")) {
                        if ("1".equals(modelAdapter.getString("all_device")) || 1 == 1) {
                            ClusterSerfSyncManager.sendData(RowToSerfManager.buildRowToSerf(modelAdapter, insertSql));
                            PersonAManager.savePersonAFromPerson(modelAdapter);
                        }
                    } else {
                        ClusterSerfSyncManager.sendData(RowToSerfManager.buildRowToSerf(modelAdapter, insertSql));
                    }
                }
                if (Constants.printSql) {
                    System1.out.println("insertsql=" + insertSql + " " + FrameUtil.getFrames());
                }
                DatabaseManager.execSQL(insertSql);
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
            System.out.println("BaseManager.save sql=" + insertSql);
        }
    }
 
    public static void deleteWithDelFlag(ModelAdapter modelAdapter) {
        try {
            String table = modelAdapter.getString("table");
            String id = modelAdapter.getString("id");
            String del_flag = "1";
            if (syncTableNames.contains(table)) {
                id = Base64Util.encodeToString(table, "id", id);
                del_flag = Base64Util.encodeToString(table, "del_flag", del_flag);
            }
            String sql = "update " + table + " set del_flag='" + del_flag + "' where id='" + id + "'";
            if (Constants.printSql) {
                System1.out.println("deletesql=" + sql + " " + FrameUtil.getFrames());
            }
            if (
                    syncTableNames.contains(table) &&
                            !Constants.FALSE.equals(modelAdapter.getString(Sync.needSync))
                    ) {
                ClusterSerfSyncManager.sendData(RowToSerfManager.buildRowToSerf(modelAdapter, sql));
            }
            DatabaseManager.execSQL(sql);
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        }
    }
 
    public static void delete(ModelAdapter modelAdapter) {
        if (modelAdapter != null) {
            if (Constants.deletePersonPhysical) {
                deletePhysically(modelAdapter);
            } else {
                try {
                    String table = modelAdapter.getString("table");
                    String id = modelAdapter.getString("id");
                    String del_flag = "1";
                    if (syncTableNames.contains(table)) {
                        id = Base64Util.encodeToString(table, "id", id);
                        del_flag = Base64Util.encodeToString(table, "del_flag", del_flag);
                    }
                    String sql = "update " + table + " set del_flag='" + del_flag + "' where id='" + id + "'";
                    if (Constants.printSql) {
                        System1.out.println("deletesql=" + sql + " " + FrameUtil.getFrames());
                    }
                    if (
                            syncTableNames.contains(table) &&
                                    !Constants.FALSE.equals(modelAdapter.getString(Sync.needSync))
                            ) {
                        ClusterSerfSyncManager.sendData(RowToSerfManager.buildRowToSerf(modelAdapter, sql));
                    }
                    DatabaseManager.execSQL(sql);
                } catch (Exception e) {
                    ExceptionUtil.printException(e);
                }
            }
        }
    }
 
    public static void deletePhysically(ModelAdapter modelAdapter) {
        try {
            if (modelAdapter != null) {
                String table = modelAdapter.getString("table");
                String id = modelAdapter.getString("id");
                String sql = "delete from " + table + " where id='" + id + "'";
                if (Constants.printSql) {
                    System1.out.println("deletesql=" + sql + " " + FrameUtil.getFrames());
                }
                if (
                        syncTableNames.contains(table) &&
                                !Constants.FALSE.equals(modelAdapter.getString(Sync.needSync))
                        ) {
                    ClusterSerfSyncManager.sendData(RowToSerfManager.buildRowToSerf(modelAdapter, sql));
                }
                try {
                    DatabaseManager.execSQL(sql);
                } catch (SQLException e) {
                    System1.out.println("sql=" + sql);
                    ExceptionUtil.printException(e);
                }
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        }
    }
 
    public static ModelAdapter cursorToModelAdapter(Cursor cursor, String table) {
        ModelAdapter modelAdapter = new ModelAdapter();
        String[] columnNames = cursor.getColumnNames();
        for (String columnName : columnNames) {
            modelAdapter.setString(columnName, cursor.getString(cursor.getColumnIndex(columnName)));
        }
        for (Map.Entry<String, Object> entry : modelAdapter.model.entrySet()) {
            String key = entry.getKey();
            String value = (String) entry.getValue();
            if (!"camera_image_feature".equals(key)) {
                if (!TextUtils.isEmpty(value)) {
                    try {
                        modelAdapter.setString(key, Base64Util.decodeToString(table, key, value));
                    } catch (Exception e) {
                        ExceptionUtil.printException(e);
                    }
                }
            }
        }
        return modelAdapter;
    }
 
    public static ModelAdapter findById(String table, String id) {
        Cursor cursor = null;
        try {
            if (id == null) {
                return null;
            }
            cursor = DatabaseManager.getDatabase().rawQuery("select * from " + table + " where id = '" + id + "'", null);
            if (cursor.moveToFirst()) {
                return cursorToModelAdapter(cursor, table);
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
 
    public static ModelAdapter findByTime(String table, String time) {
        Cursor cursor = null;
        try {
            cursor = DatabaseManager.getDatabase().rawQuery("select * from " + table + " where visit_time = '" + time + "'", null);
            if (cursor.moveToFirst()) {
                return cursorToModelAdapter(cursor, table);
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
 
    public static ModelAdapter findOne(String sql) {
        Cursor cursor = null;
        try {
            if (Constants.printSql) {
                System1.out.println("findOne sql=" + sql + " " + FrameUtil.getFrames());
            }
            cursor = DatabaseManager.getDatabase().rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                return cursorToModelAdapter(cursor, getTableName(sql));
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }
 
    private static String getTableName(String sql) {
        try {
            return sql.toLowerCase().substring(sql.indexOf("from") + "from".length()).trim().split(" ")[0].trim();
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        }
        return "";
    }
 
    public static List<ModelAdapter> findList(String sql) {
        return findList(Constants.baseDatabasePath, sql);
    }
 
    public static List<ModelAdapter> findList(String databasePath, String sql) {
        List<ModelAdapter> modelAdapterList = new ArrayList<>();
        Cursor cursor = null;
        try {
            if (Constants.printSql) {
                System1.out.println("sql=" + sql + " " + FrameUtil.getFrames()
                );
            }
            cursor = DatabaseManager.getDatabase(databasePath).rawQuery(sql, null);
            if (cursor.moveToFirst()) {
                while (!cursor.isAfterLast()) {
                    modelAdapterList.add(cursorToModelAdapter(cursor, getTableName(sql)));
                    cursor.moveToNext();
                }
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return modelAdapterList;
    }
 
    public static void deleteList(List<ModelAdapter> modelAdapterList) {
        for (ModelAdapter modelAdapter : modelAdapterList) {
            FeatureManager.removeFeature(modelAdapter.getString(Person.id));
            deletePhysically(modelAdapter);
        }
    }
 
    public static Map<String, String> parseSql(String sql) {
        Map<String, String> tableKeyValueMap = new HashMap<>();
        try {
            String[] split = sql.split("\\(`");
            String[] values = split[1].split("VALUES");
            String keyList = values[0].trim().substring(0, values[0].length() - 3);
            String valueList = values[1].trim().substring(2, values[1].length() - 3);
            String[] keyString = keyList.split("`,`");
            String[] valueString = valueList.split("','");
            if (keyString.length == valueString.length) {
                for (int i = 0; i < keyString.length; i++) {
                    tableKeyValueMap.put(keyString[i], valueString[i]);
                }
            }
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        }
        return tableKeyValueMap;
    }
 
    public static void executeSqlInLocal(String databasePath, String sql) {
        try {
            DatabaseManager.getDatabase(databasePath).execSQL(sql);
        } catch (Exception e) {
            ExceptionUtil.printException(e);
        }
    }
 
    public static void saveFromMap(Object modelAdapterMap) {
        if (modelAdapterMap != null) {
            ModelAdapter modelAdapter = new ModelAdapter();
            modelAdapter.model = (Map<String, Object>) modelAdapterMap;
            save(modelAdapter);
        }
    }
 
    public static class GetInsertOrUpdateSql {
        private ModelAdapter modelAdapter;
        private String table;
        private String insertSql;
 
        public GetInsertOrUpdateSql(ModelAdapter modelAdapter) {
            this.modelAdapter = modelAdapter;
        }
 
        public String getTable() {
            return table;
        }
 
        public String getInsertSql() {
            return insertSql;
        }
 
        public GetInsertOrUpdateSql invoke() {
            Map<String, Object> sqliteModel = modelAdapter.model;
            table = (String) sqliteModel.get("table");
            insertSql = "INSERT OR REPLACE INTO " + table + " ";
            List<String> paramNameList = new ArrayList<>();
            List<String> paramValueList = new ArrayList<>();
            String id = (String) sqliteModel.get("id");
            if (id == null) {
                id = UUID.randomUUID().toString();
                sqliteModel.put("id", id);
            }
            List<String> columnsNameList = tableColumnNames.get(table);
            boolean hasDelFlag = false;
            if (columnsNameList != null) {
                for (Map.Entry<String, Object> entry : sqliteModel.entrySet()) {
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (columnsNameList.contains(key)) {
                        if (key.contains("del_flag") && !TextUtils.isEmpty((String) value)) {
                            hasDelFlag = true;
                        }
                        paramNameList.add("`" + key + "`");
                        if (value == null) {
                            paramValueList.add("''");
                        } else {
                            if (value instanceof byte[]) {
                                paramValueList.add(ModelAdapter.getAttachmentPath(id, key, table));
                            } else {
                                StringBuffer sb = new StringBuffer();
                                sb.append("'");
                                sb.append(value);
                                sb.append("'");
                                paramValueList.add(sb.toString());
                            }
                        }
                    }
                }
                if (!hasDelFlag) {
                    if (columnsNameList.contains("del_flag")) {
                        paramNameList.add("`del_flag`");
                        paramValueList.add("'0'");
                    }
                }
                if (syncTableNames.contains(table)) {
                    for (int i = 0; i < paramNameList.size(); i++) {
                        String key = paramNameList.get(i);
                        String value = paramValueList.get(i);
                        String strValue = value;
                        if (value != null && !TextUtils.isEmpty(value) && !"''".equals(strValue)) {
                            if (!"`camera_image_feature`".equals(key)) {
                                try {
                                    if (strValue.startsWith("'")) {
                                        strValue = strValue.substring(1, strValue.length());
                                    }
                                    if (strValue.endsWith("'")) {
                                        strValue = strValue.substring(0, strValue.length() - 1);
                                    }
                                    strValue = Base64Util.encodeToString(table, key, strValue);
                                    paramValueList.set(i, "'" + strValue + "'");
                                } catch (Exception e) {
                                    ExceptionUtil.printException(e);
                                }
                            }
                        }
                    }
                }
                insertSql += "(" + TextUtils.join(",", paramNameList) + ") VALUES (" +
                        TextUtils.join(",", paramValueList) + ")";
            }
            return this;
        }
    }
}