13693261870
2025-06-24 8565bd83fcd670ec8379084d600eb97d18037d21
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
package com.terra.system.helper;
 
import com.terra.system.entity.all.BaseGeoEntity;
import com.terra.system.entity.all.StaticData;
import com.terra.system.mapper.all.BasicMapper;
import com.terra.system.mapper.all.GeomBaseMapper;
import com.terra.system.service.all.BaseQueryService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gdal.ogr.*;
import org.gdal.osr.CoordinateTransformation;
import org.gdal.osr.SpatialReference;
import org.gdal.osr.osr;
 
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * GDB帮助类
 * @author WWW
 */
public class GdbHelper {
    private final static Log log = LogFactory.getLog(GdbHelper.class);
 
    /**
     * 销毁资源
     */
    public static void delete(Layer layer) {
        try {
            if (null != layer) {
                layer.delete();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
 
    /**
     * 销毁资源
     */
    public static void delete(DataSource dataSource, Driver driver) {
        try {
            if (null != dataSource) {
                dataSource.delete();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
 
        try {
            if (null != driver) {
                driver.delete();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
 
    /**
     * 销毁资源
     */
    public static void delete(Layer layer, DataSource dataSource, Driver driver) {
        delete(layer);
        delete(dataSource, driver);
    }
 
    /**
     * 获取表名
     */
    public static List<String> getTabNames(String filePath) {
        List<String> list = new ArrayList<>();
 
        Driver driver = null;
        DataSource dataSource = null;
        try {
            // driver = ogr.GetDriverByName("OpenFileGDB")
            driver = ogr.GetDriverByName("FileGDB");
            if (null == driver) {
                log.error("GdbHelper.getTabNames.driver is null.");
                return list;
            }
 
            dataSource = driver.Open(filePath, 0);
            if (null == dataSource) {
                log.error("GdbHelper.getTabNames.dataSource is null. " + filePath);
                return list;
            }
 
            for (int i = 0, count = dataSource.GetLayerCount(); i < count; i++) {
                Layer layer = dataSource.GetLayer(i);
                list.add(layer.GetName());
 
                layer.delete();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            GdbHelper.delete(dataSource, driver);
        }
 
        return list;
    }
 
    /**
     * 读取数据
     */
    public static <T> List<T> readData(Class clazz, String filePath, String layerName, boolean isTransform) {
        List<T> list = new ArrayList<>();
 
        Driver driver = null;
        DataSource dataSource = null;
        try {
            // driver = ogr.GetDriverByName("OpenFileGDB")
            driver = ogr.GetDriverByName("FileGDB");
            if (null == driver) {
                return list;
            }
 
            dataSource = driver.Open(filePath, 0);
            if (null == dataSource) {
                return list;
            }
 
            for (int i = 0, count = dataSource.GetLayerCount(); i < count; i++) {
                Layer layer = dataSource.GetLayer(i);
                if (layer.GetName().equals(layerName)) {
                    GdbHelper.readLayer(clazz, layer, list, isTransform);
                    break;
                }
 
                layer.delete();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            GdbHelper.delete(dataSource, driver);
        }
 
        return list;
    }
 
    /**
     * 读取图层
     */
    public static <T> void readLayer(Class clazz, Layer layer, List<T> list, boolean isTransform) {
        try {
            Field gField = getGeomField(clazz);
 
            Map<Integer, Field> map = new HashMap<>(3);
            getFieldMapper(clazz, layer, map);
            if (map.isEmpty() || 0 == layer.GetFeatureCount()) {
                return;
            }
 
            CoordinateTransformation ct = getCoordinateTransformation(layer, isTransform);
 
            do {
                Feature f = layer.GetNextFeature();
                if (null == f) {
                    break;
                }
 
                T t = (T) clazz.newInstance();
                readFeature(t, f, map, gField, ct);
                list.add(t);
            } while (true);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        } finally {
            GdbHelper.delete(layer);
        }
    }
 
    /**
     * 获取坐标转换器
     */
    private static CoordinateTransformation getCoordinateTransformation(Layer layer, boolean isTransform) {
        if (!isTransform) {
            return null;
        }
 
        String epsg = layer.GetSpatialRef().GetAttrValue("AUTHORITY", 1);
        if (StringHelper.isEmpty(epsg)) {
            return null;
        }
 
        int epsgId = Integer.parseInt(epsg);
        if (StaticData.I4326 == epsgId || StaticData.I4490 == epsgId) {
            return null;
        }
 
        SpatialReference srTarget = new SpatialReference();
        srTarget.ImportFromEPSG(StaticData.I4490);
 
        layer.GetSpatialRef().SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER);
        srTarget.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER);
 
        return CoordinateTransformation.CreateCoordinateTransformation(layer.GetSpatialRef(), srTarget);
    }
 
    /**
     * 获取 geom 字段
     */
    private static Field getGeomField(Class clazz) {
        try {
            Field gField = clazz.getSuperclass().getDeclaredField("geom");
            gField.setAccessible(true);
 
            return gField;
        } catch (Exception ex) {
            return null;
        }
    }
 
    /**
     * 获取字段映射
     */
    private static void getFieldMapper(Class clazz, Layer layer, Map<Integer, Field> map) {
        try {
            FeatureDefn fd = layer.GetLayerDefn();
            for (int i = 0, count = fd.GetFieldCount(); i < count; i++) {
                try {
                    String name = fd.GetFieldDefn(i).GetName().toLowerCase();
                    if (StaticData.READ_EXCLUDE_FIELDS.contains(name)) {
                        continue;
                    }
 
                    Field field = clazz.getDeclaredField("gbcode".equals(name) ? "gb" : name);
                    field.setAccessible(true);
 
                    map.put(i, field);
                } catch (Exception e) {
                    //
                }
            }
 
            if (!StaticData.OBJECT.equals(clazz.getSuperclass().getName())) {
                getFieldMapper(clazz.getSuperclass(), layer, map);
            }
        } catch (Exception ex) {
            log.error(ex);
        }
    }
 
    /**
     * 读取Feature
     */
    private static <T> void readFeature(T t, Feature f, Map<Integer, Field> map, Field gField, CoordinateTransformation ct) {
        for (Integer i : map.keySet()) {
            try {
                Field field = map.get(i);
                setValue(t, f, field, i);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
 
        if (null != gField) {
            setGeom(t, gField, f.GetGeometryRef(), ct);
        }
    }
 
    /**
     * 设置值
     */
    public static <T> void setValue(T t, Feature f, Field field, Integer i) throws Exception {
        switch (field.getType().getName()) {
            case "java.math.BigDecimal":
                double dd = f.GetFieldAsDouble(i);
                field.set(t, BigDecimal.valueOf(dd));
                break;
            case "java.lang.Double":
            case "double":
                field.set(t, f.GetFieldAsDouble(i));
                break;
            case "java.lang.Long":
            case "long":
                field.set(t, f.GetFieldAsInteger64(i));
                break;
            case "java.lang.Integer":
            case "int":
                field.set(t, f.GetFieldAsInteger(i));
                break;
            case "java.sql.Timestamp":
                Timestamp ts = getTimestamp(f, i);
                if (null != ts) {
                    field.set(t, ts);
                }
                break;
            case "java.time.LocalDate":
                LocalDate ld = getLocalDate(f, i);
                if (null != ld) {
                    field.set(t, ld);
                }
                break;
            default:
                field.set(t, f.GetFieldAsString(i));
                break;
        }
    }
 
    /**
     * 设置 geom 字段值
     * <p>
     * wkbUnknown = 0,
     * wkbPoint = 1,
     * wkbLineString = 2,
     * wkbPolygon = 3,
     * wkbMultiPoint = 4,
     * wkbMultiLineString = 5,
     * wkbMultiPolygon = 6,
     * wkbGeometryCollection = 7,
     * wkbNone = 100,
     * wkbLinearRing = 101
     */
    private static <T> void setGeom(T t, Field gField, Geometry geometry, CoordinateTransformation ct) {
        try {
            if (null == geometry) {
                gField.set(t, "null");
                return;
            }
            if (null != ct) {
                int flag = geometry.Transform(ct);
            }
 
            String wkt = geometry.ExportToWkt();
            if (wkt.contains(StaticData.LINESTRING) && !wkt.contains(StaticData.MULTILINESTRING)) {
                wkt = wkt.replace("LINESTRING (", "MULTILINESTRING ((") + ")";
            }
            if (wkt.contains(StaticData.POLYGON) && !wkt.contains(StaticData.MULTIPOLYGON)) {
                wkt = wkt.replace("POLYGON (", "MULTIPOLYGON ((") + ")";
            }
            wkt = wkt.replace(" 0,", ",").replace(" 0)", ")");
            if (wkt.contains(StaticData.MULTICURVE)) {
                wkt = wkt.replace("MULTICURVE (", "MULTILINESTRING (").replace("CIRCULARSTRING ", "");
                if (wkt.contains(StaticData.COMPOUNDCURVE)) {
                    wkt = wkt.replace("COMPOUNDCURVE (", "").replace(")))", "))");
                }
            }
 
            gField.set(t, String.format("ST_GeomFromText('%s')", wkt));
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
 
    /**
     * 获取 Timestamp
     */
    public static Timestamp getTimestamp(Feature f, int index) {
        int[] pnYear = new int[1];
        int[] pnMonth = new int[1];
        int[] pnDay = new int[1];
        int[] pnHour = new int[1];
        int[] pnMinute = new int[1];
        float[] pfSecond = new float[1];
        int[] pnTzFlag = new int[1];
 
        f.GetFieldAsDateTime(index, pnYear, pnMonth, pnDay, pnHour, pnMinute, pfSecond, pnTzFlag);
 
        float fSecond = pfSecond[0];
        int s = (int) fSecond;
        int ns = (int) (1000000000 * fSecond - s);
 
        if (pnYear[0] > StaticData.I2050 || pnMonth[0] > StaticData.I12 || pnDay[0] > StaticData.I31 || pnHour[0] > StaticData.I24 || pnMinute[0] > StaticData.I60) {
            return null;
        }
 
        LocalDateTime localDateTime = LocalDateTime.of(
                LocalDate.of(pnYear[0], pnMonth[0], pnDay[0]),
                LocalTime.of(pnHour[0], pnMinute[0], s, ns)
        );
 
        return Timestamp.valueOf(localDateTime);
    }
 
    /**
     * 获取 LocalDate
     */
    public static LocalDate getLocalDate(Feature f, int index) {
        int[] pnYear = new int[1];
        int[] pnMonth = new int[1];
        int[] pnDay = new int[1];
        int[] pnHour = new int[1];
        int[] pnMinute = new int[1];
        float[] pfSecond = new float[1];
        int[] pnTzFlag = new int[1];
 
        f.GetFieldAsDateTime(index, pnYear, pnMonth, pnDay, pnHour, pnMinute, pfSecond, pnTzFlag);
        if (pnYear[0] > StaticData.I2050 || pnMonth[0] > StaticData.I12 || pnDay[0] > StaticData.I31) {
            return null;
        }
 
        return LocalDate.of(pnYear[0], pnMonth[0], pnDay[0]);
    }
 
    /**
     * 创建GDB
     */
    public static void createGdb(String filePath,  Map<String, List<?>> map) throws Exception {
        Driver driver = null;
        DataSource dataSource = null;
        try {
            driver = ogr.GetDriverByName("FileGDB");
            if (null == driver) {
                log.error("GdbHelper.createGdb.driver(FileGDB) is null.");
                return;
            }
            dataSource = driver.CreateDataSource(filePath, null);
            if (null == dataSource) {
                log.error("GdbHelper.createGdb.dataSource is null. " + filePath);
                return;
            }
 
            for (String key : map.keySet()) {
                Layer layer = null;
                try {
                    BasicMapper baseMapper = ClassHelper.getBasicMapper(key);
                    if (null == baseMapper) {
                        continue;
                    }
                    layer = createLayer(dataSource, baseMapper);
                    if (null == layer) {
                        continue;
                    }
 
                    String className = ClassHelper.getClassName(baseMapper);
                    Class clazz = ClassHelper.getEntityClass(className);
                    if (null == clazz) {
                        continue;
                    }
 
                    List<Field> fields = new ArrayList<>();
                    getFields(clazz, fields, StaticData.GDB_EXCLUDE_FIELDS);
                    addLayerField(layer, fields);
 
                    setLayerData(layer, fields, map.get(key));
                } finally {
                    if (null != layer) {
                        layer.delete();
                    }
                }
            }
 
            dataSource.SyncToDisk();
            dataSource.FlushCache();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw ex;
        } finally {
            GdbHelper.delete(dataSource, driver);
        }
    }
 
    /**
     * 创建图层
     */
    private static Layer createLayer(DataSource dataSource, BasicMapper baseMapper ) {
        String tab = BaseQueryService.getTabName(baseMapper);
        if (StringHelper.isNull(tab)) {
            return null;
        }
 
        Integer srid = null;
        String geomType = null;
        if (baseMapper instanceof GeomBaseMapper) {
            GeomBaseMapper geomMapper = (GeomBaseMapper) baseMapper;
            geomType = geomMapper.selectGeometryType(tab);
 
            srid = geomMapper.selectSrid(tab);
        }
 
        SpatialReference sr = new SpatialReference();
        sr.ImportFromEPSG(null == srid ? 4490 : srid);
 
        return dataSource.CreateLayer(tab.replace(".", "_"), sr, getGeomType(geomType), null);
    }
 
    /**
     * 获取Geom类别
     */
    private static Integer getGeomType(String geomType) {
        if (StringHelper.isEmpty(geomType)) {
            return ogr.wkbPoint;
        }
 
        switch (geomType) {
            case "ST_Point":
                return ogr.wkbPoint;
            case "ST_MultiPoint":
                return ogr.wkbMultiPoint;
            case "ST_LineString":
                return ogr.wkbLineString;
            case "ST_MultiLineString":
                return ogr.wkbMultiLineString;
            case "ST_Polygon":
                return ogr.wkbPolygon;
            case "ST_MultiPolygon":
                return ogr.wkbMultiPolygon;
            default:
                return ogr.wkbUnknown;
        }
    }
 
    /**
     * 获取字段
     */
    public static void getFields(Class clazz, List<Field> list, List<String> excludeFields) {
        try {
            Field[] fields = clazz.getDeclaredFields();
            for (Field f : fields) {
                if (excludeFields.contains(f.getName())) {
                    continue;
                }
 
                f.setAccessible(true);
                list.add(f);
            }
 
            if (!StaticData.OBJECT.equals(clazz.getSuperclass().getName())) {
                getFields(clazz.getSuperclass(), list, excludeFields);
            }
        } catch (Exception ex) {
            //
        }
    }
 
    /**
     * 添加图层字段
     */
    public static void addLayerField(Layer layer, List<Field> list) {
        for (int i = 0, c = list.size(); i < c; i++) {
            Field f = list.get(i);
 
            int fieldType = getFieldType(f);
            FieldDefn fd = new FieldDefn(f.getName(), fieldType);
 
            layer.CreateField(fd, i + 1);
        }
    }
 
    /**
     * 获取字段类型
     */
    private static Integer getFieldType(Field f) {
        switch (f.getType().getName()) {
            case "java.math.BigDecimal":
            case "java.lang.Double":
            case "double":
                return ogr.OFTReal;
            case "java.lang.Long":
            case "long":
                return ogr.OFTInteger64;
            case "java.lang.Integer":
            case "int":
                return ogr.OFTInteger;
            case "java.sql.Timestamp":
                return ogr.OFTDateTime;
            case "java.time.LocalDate":
                return ogr.OFTDate;
            default:
                return ogr.OFTString;
        }
    }
 
    /**
     * 设置图层数据
     */
    private static <T> void setLayerData(Layer layer,  List<Field> fields, List<T> list) throws Exception {
        for (T t : list) {
            Feature f = new Feature(layer.GetLayerDefn());
 
            if (t instanceof BaseGeoEntity) {
                BaseGeoEntity geoEntity = (BaseGeoEntity) t;
                if (!StringHelper.isEmpty(geoEntity.getGeom())) {
                    Geometry geom = Geometry.CreateFromWkt(geoEntity.getGeom());
                    f.SetGeometry(geom);
                }
            }
 
            setFeatureData(f, fields, t);
            layer.CreateFeature(f);
        }
    }
 
    /**
     * 设置要素的数据
     */
    public static <T> void setFeatureData(Feature f, List<Field> fields, T t) throws Exception {
        for (int i = 0, c = fields.size(); i < c; i++) {
            Field field = fields.get(i);
            Object val = field.get(t);
            if (null == val) {
                continue;
            }
 
            switch (field.getType().getName()) {
                case "java.math.BigDecimal":
                    BigDecimal big = (BigDecimal) val;
                    f.SetField(i, big.doubleValue());
                    break;
                case "java.lang.Double":
                case "double":
                    double d = (double) val;
                    f.SetField(i, d);
                    break;
                case "java.lang.Long":
                case "long":
                    long l = (long) val;
                    f.SetField(i, l);
                    break;
                case "java.lang.Integer":
                case "int":
                    int n = (int) val;
                    f.SetField(i, n);
                    break;
                case "java.sql.Timestamp":
                    Timestamp timestamp = (Timestamp) field.get(t);
                    setTimestamp(f, i, timestamp);
                    break;
                case "java.time.LocalDate":
                    LocalDate localDate = (LocalDate) field.get(t);
                    setLocalDate(f, i, localDate);
                    break;
                default:
                    String str = (String) val;
                    f.SetField(i, str);
                    break;
            }
        }
    }
 
    /**
     * 设置Timestamp
     */
    private static void setTimestamp(Feature f, int i, Timestamp time) {
        if (null == time) {
            return;
        }
 
        LocalDateTime local = time.toLocalDateTime();
        f.SetField(i, local.getYear(), local.getMonthValue(), local.getDayOfMonth(), local.getHour(), local.getMinute(), local.getSecond(), 8);
    }
 
    /**
     * 设置LocalDate
     */
    private static void setLocalDate(Feature f, int i, LocalDate local) {
        if (null == local) {
            return;
        }
 
        f.SetField(i, local.getYear(), local.getMonthValue(), local.getDayOfMonth(), 0, 0, 0, 8);
    }
}