OWL ITS + 탐지시스템(인터넷 진흥원)
박지현
2022-03-07 398a4927e195755bd6a46be99337efd8dacc3dc2
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
package kr.wisestone.owl.util;
 
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import kr.wisestone.owl.constant.MsgConstants;
import kr.wisestone.owl.exception.OwlRuntimeException;
import kr.wisestone.owl.vo.CompanyFieldVo;
import kr.wisestone.owl.vo.IspFieldVo;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
 
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
 
public class ConvertUtil {
    static final Logger LOGGER = LoggerFactory.getLogger(ConvertUtil.class);
 
    /**
     * 맵 목록을 주어진 오브젝트 목록으로 복사한다.
     *
     * @param sources
     * @param clazz
     * @param ignores
     * @return
     */
    public static <T> List<T> convertListToListClass(List<Map<String, Object>> sources,
            Class<T> clazz, String... ignores) {
        List<T> targets = new ArrayList<T>();
 
        for (Map<String, Object> source : sources) {
            targets.add(convertMapToClass(source, clazz, ignores));
        }
 
        return targets;
    }
 
    public static <T> List<T> convertListToListClass(List<Map<String, Object>> sources,
            Class<T> clazz) {
        return convertListToListClass(sources, clazz, new String[] {});
    }
 
    /**
     * 맵 오브젝트를 주어진 클래스 오브젝트의 필드로 복사한다.
     *
     * @param source
     * @param clazz
     * @param ignores
     *            매핑에서 제외할 필드
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertMapToClass(Map<String, Object> source, Class<T> clazz, String... ignores) {
        Object objClass = null;
        try {
            objClass = clazz.newInstance();
        } catch (Exception e) {
            LOGGER.error("", e);
        }
        convertMapToObject(source, objClass, ignores);
 
        return (T) objClass;
    }
 
    /**
     * 맵 오브젝트를 주어진 오브젝트의 필드로 복사한다.
     *
     * @param map
     * @param objClass
     * @param ignores
     * @return
     */
    public static Object convertMapToObject(Map<String, Object> map,
            Object objClass, String... ignores) {
        String keyAttribute = null;
        Iterator<String> itr = map.keySet().iterator();
        while (itr.hasNext()) {
            keyAttribute = itr.next();
 
            if (ArrayUtils.contains(ignores, keyAttribute)) {
                continue;
            }
            if (map.get(keyAttribute) == null) {
                continue;
            }
 
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(objClass.getClass(), keyAttribute);
            try {
                Method method = propertyDescriptor.getWriteMethod();
 
                if (propertyDescriptor.getPropertyType() == String.class) {
                    //  xss 방어를 위해 script 문자 공백 치환
                    method.invoke(objClass, CommonUtil.preventXss(map.get(keyAttribute).toString()));
                } else if (propertyDescriptor.getPropertyType() == Integer.class) {
                    method.invoke(objClass, new Integer(map.get(keyAttribute).toString()));
                } else if (propertyDescriptor.getPropertyType() == Long.class) {
                    method.invoke(objClass, Long.valueOf(map.get(keyAttribute).toString()));
                }
                else if (propertyDescriptor.getPropertyType() == Double.class) {
                    method.invoke(objClass, Double.valueOf(map.get(keyAttribute).toString()));
                }
                else if (propertyDescriptor.getPropertyType() == Boolean.class) {
                    if ("Y".equalsIgnoreCase(map.get(keyAttribute).toString())) {
                        method.invoke(objClass, Boolean.TRUE);
                    } if ("true".equalsIgnoreCase(map.get(keyAttribute).toString())) {
                        method.invoke(objClass, Boolean.TRUE);
                    } else {
                        method.invoke(objClass, Boolean.FALSE);
                    }
                }
            } catch (Exception e) {
//                e.printStackTrace();
            }
        }
        return objClass;
    }
 
    /**
     * 주어진 오브젝트 목록(List)을 주어진 클래스 목록으로 복사한다.
     *
     * @param sources
     * @param targetClass
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <S, T> List<T> convertObjectsToClasses(
            List<S> sources, Class<T> targetClass) {
        List<T> targets = new ArrayList<T>();
        Object target = null;
 
        Iterator<S> iterator = sources.iterator();
        while (iterator.hasNext()) {
            S source = iterator.next();
 
            try {
                target = targetClass.newInstance();
                copyProperties(source, target);
 
                targets.add((T) target);
            } catch (Exception e) {
                throw new OwlRuntimeException(e);
            }
        }
 
        return targets;
    }
 
    /**
     * 주어진 오브젝트 목록(Set)을 주어진 클래스 목록으로 복사한다.
     *
     * @param sources
     * @param targetClass
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <S, T> List<T> convertObjectsToClasses(
            Set<S> sources, Class<T> targetClass) {
        List<T> targets = new ArrayList<T>();
        Object target = null;
 
        Iterator<S> iterator = sources.iterator();
        while (iterator.hasNext()) {
            S source = iterator.next();
 
            try {
                target = targetClass.newInstance();
                copyProperties(source, target);
 
                targets.add((T) target);
            } catch (Exception e) {
                throw new OwlRuntimeException(e);
            }
        }
 
        return targets;
    }
 
    /**
     * 오브젝트 속성을 맵에 복사하여 맵을 반환한다.
     *
     * @param source
     * @return
     */
    public static Map<String, Object> convertObjectToMap(Object source) {
        return convertObjectToMap(source, new String[] {});
    }
 
    /**
     * 오브젝트 속성에서 ignores 필드를 제외하고 맵에 복사하여 맵을 반환한다.
     *
     * @param source
     * @param ignores
     * @return
     */
    public static Map<String, Object> convertObjectToMap(Object source, String...ignores) {
        Map<String, Object> target = new HashMap<String, Object>();
 
        if (source == null) {
            throw new OwlRuntimeException(MsgConstants.SOURCE_OBJECT_IS_NULL);
        }
 
        try {
            copyAttrSourceToTarget(source, target, ignores);
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_OBJECT, e);
        }
 
        return target;
    }
 
    private static void copyAttrSourceToTarget(Object source, Object target,
            String... ignores) {
        copyAttrSourceToTarget(source, target, false, ignores);
    }
 
    /**
     * 소스 오브젝트 속성에서 ignores 필드를 제외하고 타겟 오브젝트로 속성을 복사한다.
     *
     * @param source
     * @param target
     * @param ignores
     */
    @SuppressWarnings("unchecked")
    private static void copyAttrSourceToTarget(Object source, Object target, boolean chkEqual,
            String... ignores) {
        PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(source.getClass());
        if (propertyDescriptors == null || propertyDescriptors.length == 0) {
            LOGGER.debug("속성이 존재하지 않는다. : " + source.getClass().getName());
            return;
        }
 
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (ignores != null && ignores.length > 0) {
                if (ArrayUtils.contains(ignores, propertyDescriptor.getName())) {
                    LOGGER.debug("무시될 필드 항목이다 : " + propertyDescriptor.getName());
                    continue;
                }
            }
 
            if (propertyDescriptor.getPropertyType() == Integer.class ||
                propertyDescriptor.getPropertyType() == Double.class    ||
                propertyDescriptor.getPropertyType() == Long.class    ||
                propertyDescriptor.getPropertyType() == Boolean.class ||
                propertyDescriptor.getPropertyType() == Date.class ||
                propertyDescriptor.getPropertyType() == String.class) {
                if (target instanceof Map) {
                    if (copyAttrObjectToMap(source, propertyDescriptor.getName(), (Map<String, Object>) target) == false) {
                        continue;
                    }
                } else {
                    if (copyAttrObjectToObject(source, propertyDescriptor.getName(), target, chkEqual) == false) {
                        continue;
                    }
                }
            } else {
//                LogUtil.debug(LOGGER, field.getName() + "(" + field.getType().getName() + ")은 지원 타입이 아니다.");
            }
        }
    }
 
    /**
     * 주어진 타입의 모든 속성(필드)을 반환한다.
     *
     * @param fields
     * @param type
     * @return
     */
    public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
        for (Field field: type.getDeclaredFields()) {
            fields.add(field);
        }
 
        if (type.getSuperclass() != null) {
            fields = getAllFields(fields, type.getSuperclass());
        }
 
        return fields;
    }
 
    /**
     * 주어진 오브젝트에서 주어진 필드를 맵에 복사한다.
     *
     * @param source
     * @param fieldName
     * @param target
     *
     * @return
     */
    private static boolean copyAttrObjectToMap(Object source, String fieldName, Map<String, Object> target) {
        PropertyDescriptor sourcePropertyDescriptor = BeanUtils.getPropertyDescriptor(source.getClass(), fieldName);
 
        Method get = null;
        try {
            get = sourcePropertyDescriptor.getReadMethod();
        } catch (Exception e) {
            return false;
        }
 
        Object value = null;
        try {
            value = get.invoke(source, new Object[] {});
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_OBJECT, e);
        }
        if (value != null) {
            if (value instanceof Date) {
                target.put(fieldName, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) value));
            } else {
                target.put(fieldName, value);
            }
        }
 
        return true;
    }
 
    /**
     * 소스 오브젝트에서 주어진 필드를 타겟 오브젝트에 복사한다.
     *
     * @param source
     * @param fieldName
     * @param target
     *
     * @return
     */
    private static boolean copyAttrObjectToObject(Object source, String fieldName, Object target, boolean chkEqual) {
        Object sourceValue = null;
 
        PropertyDescriptor sourcePropertyDescriptor = BeanUtils.getPropertyDescriptor(source.getClass(), fieldName);
        PropertyDescriptor targetPropertyDescriptor = BeanUtils.getPropertyDescriptor(target.getClass(), fieldName);
 
        if (sourcePropertyDescriptor == null || targetPropertyDescriptor == null) {
            return false;
        }
 
        Method set = null;
        Method sourceGetMethod = null;
        Method targetGetMethod = null;
        try {
            sourceGetMethod = sourcePropertyDescriptor.getReadMethod();
            targetGetMethod = targetPropertyDescriptor.getReadMethod();
 
            sourceValue = sourceGetMethod.invoke(source, new Object[] {});
            if (chkEqual) {
                Object targetValue = targetGetMethod.invoke(target, new Object[] {});
 
                if (sourceValue == null && targetValue == null) {
                    return true;
                } else if (sourceValue != null && sourceValue.equals(targetValue)) {
                    return true;
                } else if (targetValue != null && targetValue.equals(sourceValue)) {
                    return true;
                }
            }
        } catch (Exception e) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("fieldName : " + fieldName, e);
            }
            return false;
        }
 
        try {
            if (sourcePropertyDescriptor.getPropertyType() == Date.class) {
                set = target.getClass().getMethod(targetPropertyDescriptor.getWriteMethod().getName(), String.class);
            } else {
                set = targetPropertyDescriptor.getWriteMethod();
            }
        } catch (Exception e) {
            LOGGER.error("", e);
            return false;
        }
 
 
        try {
            if (sourceValue != null) {
                LOGGER.debug("sourceValue : " + sourceValue);
                LOGGER.debug("Set Method : " + set.toString());
 
                if (sourcePropertyDescriptor.getPropertyType() == Date.class) {
                    set.invoke(target, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) sourceValue));
                } else {
                    set.invoke(target, sourceValue);
                }
            }
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_OBJECT, e);
        }
 
        return true;
    }
 
    /**
     * 소스 오브젝트에서 Primitive Type(ignores 제외)만 타겟 클래스 오브젝트로 복사한다.
     *
     * @param source
     * @param targetClass
     * @param ignores
     * @return
     */
    public static <T> T copyProperties(Object source, Class<T> targetClass, String...ignores) {
        T target = null;
        try {
            target = targetClass.newInstance();
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_OBJECT, e);
        }
        copyProperties(source, target, true, ignores);
 
        return target;
    }
 
    public static void copyProperties(Object source, Object target, boolean chkEqual, String...ignores) {
 
        if (source == null) {
            throw new OwlRuntimeException(MsgConstants.SOURCE_OBJECT_IS_NULL);
        }
        if (target == null) {
            throw new OwlRuntimeException(MsgConstants.TARGET_OBJECT_IS_NULL);
        }
 
        try {
            copyAttrSourceToTarget(source, target, chkEqual, ignores);
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_OBJECT, e);
        }
    }
 
    /**
     * 소스 오브젝트에서 Primitive Type(ignores 제외)만 타겟 오브젝트로 복사한다.
     *
     * @param source
     * @param target
     */
    public static void copyProperties(Object source, Object target, String...ignores) {
        copyProperties(source, target, true, ignores);
    }
 
    public static Map<String, Object> convertJsonToMap(String json) {
        Map<String, Object> content = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            content = mapper.readValue(json,
                    new TypeReference<Map<String, Object>>() {
                    });
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_JSON, e);
        }
 
        return content;
    }
 
    public static String convertObjectToJson(Object target) {
        String json;
        ObjectMapper mapper = getObjectMapper();
 
        try {
            json = mapper.writeValueAsString(target);
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_JSON, e);
        }
 
        return json;
    }
 
    public static <T> T convertJsonToObject(String json, Class<T> targetClass) {
 
        T object;
 
        ObjectMapper mapper = getObjectMapper();
 
        try {
            object = mapper.readValue(json, targetClass);
        } catch (Exception e) {
            throw new OwlRuntimeException(MsgConstants.ERR_FAILED_CONVERT_JSON, e);
        }
 
        return object;
    }
 
    public static <T> String join(List<T> objects, String fieldName, String seperate) {
        StringBuffer sb = new StringBuffer("");
        try {
            for (T object : objects) {
                PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(object.getClass(), fieldName);
                Method method = propertyDescriptor.getReadMethod();
                if (sb.length() == 0) {
                        sb.append(method.invoke(object, fieldName));
                } else {
                    sb.append(seperate).append(" ").append(method.invoke(object, fieldName));
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e.getCause());
        }
 
        return sb.toString();
    }
 
    public static <T> List<String> getFieldValues(List<T> objects, String fieldName) {
        return getFieldValues(objects, fieldName, null, null);
    }
 
    public static <T> List<String> getFieldValues(List<T> objects, String fieldName, String beforeAdd) {
        return getFieldValues(objects, fieldName, beforeAdd, null);
    }
 
    public static <T> List<String> getFieldValues(List<T> objects, String fieldName, String beforeAdd,
            String prefix) {
        List<String> fieldValues = new ArrayList<String>();
 
        if (beforeAdd != null) {
            fieldValues.add(beforeAdd);
        }
 
        try {
            for (T object : objects) {
                PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(object.getClass(), fieldName);
                Method method = propertyDescriptor.getReadMethod();
                if (prefix == null) {
                    fieldValues.add(method.invoke(object, fieldName).toString());
                } else {
                    fieldValues.add(prefix + method.invoke(object, fieldName).toString());
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e.getCause());
        }
 
        return fieldValues;
    }
 
    public static <T> String getFieldValue(T object, String fieldName) {
        Object retVal = null;
 
        if (object != null) {
            PropertyDescriptor propertyDescriptor = BeanUtils.getPropertyDescriptor(object.getClass(), fieldName);
            Method method = propertyDescriptor.getReadMethod();
            try {
                retVal = method.invoke(object, fieldName);
            } catch (Exception e) {
                LOGGER.debug(e.toString());
            }
        }
        return retVal == null ? "" : retVal.toString();
    }
 
    private static ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }
 
    public static String[] ToArray(List<String> list) {
        return  list.toArray(new String[list.size()]);
    }
 
    /**
     * ip주소 long으로 변환
     * @param ipAddress String
     * @return long
     */
    public static long ipToLong(String ipAddress) {
        long result = 0;
        String[] ipAddressArr = ipAddress.split("\\.");
 
        for (int i=0; i<ipAddressArr.length; i++) {
            result += Integer.parseInt(ipAddressArr[i]) * Math.pow(256, 3-i);
        }
        return result;
    }
 
}