forked from geodmms/xdgnjobs

yuanhung
2016-07-07 6e74a809178ee5274148a4e957584369e2b3ab47
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
package com.ximple.eofms.jobs;
 
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import com.ximple.eofms.geoserver.config.XGeosDataConfig;
import com.ximple.eofms.geoserver.config.XGeosDataConfigMapping;
import com.ximple.eofms.jobs.context.AbstractOracleJobContext;
import com.ximple.eofms.util.PrintfFormat;
import com.ximple.eofms.util.XGeosConfigDigesterUtils;
import org.apache.commons.collections.MultiMap;
import org.apache.commons.digester3.Digester;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.Transaction;
import org.geotools.data.jdbc.JDBCUtils;
import org.opengis.feature.type.FeatureType;
import org.opengis.feature.type.GeometryDescriptor;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.xml.sax.SAXException;
 
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
 
public class GeoserverIntegrateConfigJob extends OracleConvertDgn2PostGISJob {
    final static Log logger = LogFactory.getLog(GeoserverIntegrateConfigJob.class);
 
    private static final String SKIPCONFIGJOB = "SKIPCONFIGJOB";
    private static final String MASTERMODE = "MASTERMODE";
    private static final String EPSG = "EPSG:";
    private static final String DEFAULT_NAMESPACE = "xtpc";
    private static final String XGEOSDATACONFIG_PATH = "xgeosdataconfig.xml";
    private static final String GEOSERVER_BASEURL = "GEOSERVER_URL";
    private static final String GEOSERVER_USER = "GEOSERVER_USER";
    private static final String GEOSERVER_PASS = "GEOSERVER_PASS";
 
    // private static final int MAGIC_BLOCKSIZE = (64 * 1024 * 1024) - (32 * 1024);
 
    private static final String QUERY_VIEWDEFSQL = "SELECT table_name, view_definition FROM information_schema.views " +
            "WHERE table_schema = ? AND table_name LIKE ";
 
    private static final String CREATE_VIEWSQL = "CREATE OR REPLACE VIEW \"%s\" AS SELECT * FROM \"%s\".\"%s\"";
    private static final String EXTRAWHERE_VIEWSQL = " WHERE \"%s\".level = %s AND \"%s\".symweight = %s";
 
    private static final String ALTER_VIEWSQL = "ALTER TABLE \"%s\" OWNER TO ";
    // private static final String GRANT_VIEWSQL = "GRANT SELECT ON TABLE \"%s\" TO public";
    private static final int SRSID_TWD97_ZONE119 = 3825;
    private static final int SRSID_TWD97_ZONE121 = 3826;
    public static final String DEFAULT_STORENAME = "pgDMMS";
    public static final String DEFAULT_GEODMMS_NAMESPACE = "http://tpc.ximple.com.tw/geodmms";
 
    private static XGeosDataConfigMapping xgeosDataConfigMapping = null;
 
    protected String _geoServerURL;
    protected String _geoServerUser;
    protected String _geoServerPass;
 
    private long queryTime = 0;
    private long queryTimeStart = 0;
 
    public Log getLogger() {
        return logger;
    }
 
    protected AbstractOracleJobContext prepareJobContext(String targetSchemaName, String filterPath,
                                                         boolean profileMode,
                                                         boolean useTransform) {
        return super.prepareJobContext(targetSchemaName, filterPath, profileMode, useTransform);
    }
 
    protected void extractJobConfiguration(JobDetail jobDetail) throws JobExecutionException {
        super.extractJobConfiguration(jobDetail);
 
        JobDataMap dataMap = jobDetail.getJobDataMap();
        _geoServerURL = dataMap.getString(GEOSERVER_BASEURL);
        _geoServerUser = dataMap.getString(GEOSERVER_USER);
        _geoServerPass = dataMap.getString(GEOSERVER_PASS);
 
        if (_geoServerURL == null) {
            logger.warn("GEOSERVER_URL is null");
            throw new JobExecutionException("Unknown GEOSERVER_URL.");
        }
        if (_geoServerUser == null) {
            logger.warn("GEOSERVER_USER is null");
            throw new JobExecutionException("Unknown GEOSERVER_USER.");
        }
        if (_geoServerPass == null) {
            logger.warn("GEOSERVER_PASS is null");
            throw new JobExecutionException("Unknown GEOSERVER_PASS.");
        }
    }
 
    protected XGeosDataConfigMapping getConfigMapping() {
        if (xgeosDataConfigMapping == null) {
            Digester digester = XGeosConfigDigesterUtils.getXGeosConfigDigester();
            final URL configDataURL = XGeosDataConfigMapping.class.getResource(XGEOSDATACONFIG_PATH);
            try {
                xgeosDataConfigMapping = (XGeosDataConfigMapping) digester.parse(configDataURL);
            } catch (IOException e) {
                logger.warn(e.getMessage(), e);
            } catch (SAXException e) {
                logger.warn(e.getMessage(), e);
            }
 
        }
        return xgeosDataConfigMapping;
    }
 
    private void logTimeDiff(String message, long tBefore, long tCurrent) {
        logger.warn(message + ":use time = " + ((int) ((tCurrent - tBefore) / 60000.0)) + " min - " +
                (((int) ((tCurrent - tBefore) % 60000.0)) / 1000) + " sec");
    }
 
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
 
        super.execute(jobExecutionContext);
 
        createTargetDataStore();
 
        if (getTargetDataStore() == null) {
            logger.warn("Cannot connect source postgreSQL database.");
            throw new JobExecutionException("Cannot connect source postgreSQL database.");
        }
 
        if (isProfileMode()) {
            queryTime = 0;
        }
 
        long t1 = System.currentTimeMillis();
        String targetSchemaName;
 
        try {
            logger.info("-- step:resetPostgisViewMapping --");
            long tStep = System.currentTimeMillis();
            resetPostgisViewMapping(jobExecutionContext);
            if (isProfileMode()) {
                long tStepEnd = System.currentTimeMillis();
                logTimeDiff("Profile-resetPostgisViewMapping", tStep, tStepEnd);
            }
            logger.info("-- step:resetGeoServerConfig --");
            tStep = System.currentTimeMillis();
            // resetGeoServerConfig(jobExecutionContext);
            if (isProfileMode()) {
                long tStepEnd = System.currentTimeMillis();
                logTimeDiff("Profile-resetGeoServerConfig", tStep, tStepEnd);
            }
        } finally {
            disconnect();
        }
    }
 
    /**
     * 重新建立所有重新建立所有PostGIS中的資料庫視景
     *
     * @param executionContext 批次執行的關係
     */
    private void resetPostgisViewMapping(JobExecutionContext executionContext) {
        assert executionContext != null;
        Connection connection = null;
        try {
            connection = targetDataStore.getConnection(Transaction.AUTO_COMMIT);
            String ownerName = _pgUsername;
            String currentTargetSchema = retrieveCurrentSchemaName(connection,
                DataReposVersionManager.VSSTATUS_READY);
            if (currentTargetSchema == null) {
                logger.info("Cannot found schema that status is VSSTATUS_READY[" +
                    DataReposVersionManager.VSSTATUS_READY + "]");
                return;
            }
 
            ArrayList<String> realTableNames = new ArrayList<String>();
            retrieveAllRealTableName(connection, currentTargetSchema, realTableNames);
 
            HashMap<String, String> viewDefs = retrieveViewDef(connection, "public", "fsc%");
            HashMap<String, String> tempViewDefs = retrieveViewDef(connection, "public", "indexshape%");
            viewDefs.putAll(tempViewDefs);
            tempViewDefs = viewDefs = retrieveViewDef(connection, "public", "lndtpc%");
            viewDefs.putAll(tempViewDefs);
 
            for (String tableName : realTableNames) {
                resetPostgisDataView(connection, viewDefs, ownerName, currentTargetSchema, tableName);
            }
 
            resetExtraPostgisDataView(connection, ownerName, currentTargetSchema, realTableNames);
 
            updateCurrentRepositoryStatus(connection, currentTargetSchema,
                DataReposVersionManager.VSSTATUS_LINKVIEW);
 
            String currentTargetThemesName = retrieveCurrentThemeName(connection,
                DataReposVersionManager.VSSTATUS_READY);
            if (currentTargetThemesName == null) {
                logger.info("Cannot found themes that status is VSSTATUS_READY[" +
                    DataReposVersionManager.VSSTATUS_READY + "]");
                return;
            }
 
            resetThemesBaseView(connection, ownerName, currentTargetThemesName);
 
            XGeosDataConfigMapping configMapping = getConfigMapping();
            String[] allView = retrieveTargetStoreAllViewNames(connection);
            TreeSet<String> allViewNames = new TreeSet<String>();
            if (allView != null) {
                allViewNames.addAll(Arrays.asList(allView));
            }
            List values = (List) configMapping.getMapping().get("pgOMS");
            for (Object value : values) {
                XGeosDataConfig xgeosConfig = (XGeosDataConfig) value;
                short tid = xgeosConfig.getFSC();
                short cid = xgeosConfig.getCOMP();
                StringBuilder sbTable = new StringBuilder("fsc-");
                sbTable.append(tid).append("-c-");
                sbTable.append(cid);
 
                int index = realTableNames.indexOf(sbTable.toString());
                if (index == -1) {
                    logger.debug("pgOMS LayerView Cannot found-" + xgeosConfig.toString());
                    continue;
                }
 
                StringBuilder sbView = new StringBuilder("fsc-");
                sbView.append(tid).append("-c");
                sbView.append(cid).append("-l");
                sbView.append(xgeosConfig.getLEV()).append("-w");
                sbView.append(xgeosConfig.getWEIGHT());
                String viewName = sbView.toString();
                if (allViewNames.contains(viewName)) {
                    resetThemesPostgisDataView(connection, ownerName, null, viewName);
                    if (tid == 106) {
                        resetFlowThemesPostgisDataView(connection, ownerName, null, viewName);
                    }
                }
            }
 
            updateCurrentThemeStatus(connection, currentTargetThemesName,
                DataReposVersionManager.VSSTATUS_LINKVIEW);
 
            // String[] featureNames = dataStore.getTypeNames();
            // logger.info("featureNames[] size = " + featureNames.length);
        } catch (IOException e) {
            logger.warn(e.getMessage(), e);
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
        } finally {
            if (connection != null)
                JDBCUtils.close(connection, Transaction.AUTO_COMMIT, null);
            // if (dataStore != null) dataStore.dispose();
        }
    }
 
    private void retrieveAllRealTableName(Connection connection, String targetSchema,
                                          ArrayList<String> realTableNames) throws SQLException {
        ResultSet rsMeta = null;
        try {
            rsMeta = connection.getMetaData().getTables("", targetSchema, "fsc%", new String[]{"TABLE"});
            while (rsMeta.next()) {
                String tableName = rsMeta.getString(3);
                realTableNames.add(tableName);
            }
            rsMeta.close();
            rsMeta = null;
 
            rsMeta = connection.getMetaData().getTables("", targetSchema, "index%", new String[]{"TABLE"});
            while (rsMeta.next()) {
                String tableName = rsMeta.getString(3);
                realTableNames.add(tableName);
            }
            rsMeta.close();
            rsMeta = null;
 
            rsMeta = connection.getMetaData().getTables("", targetSchema, "lndtpc%", new String[]{"TABLE"});
            while (rsMeta.next()) {
                String tableName = rsMeta.getString(3);
                realTableNames.add(tableName);
            }
        } finally {
            if (rsMeta != null) rsMeta.close();
        }
    }
 
    private void resetPostgisDataView(Connection connection, HashMap<String, String> viewDefs,
                                      String ownerName, String schemaName, String tableName) throws SQLException {
        String[] splits = tableName.split("-");
        if (splits.length > 3) {
            // feature table
 
            StringBuilder viewBuilder = new StringBuilder();
            viewBuilder.append(splits[0]);
            viewBuilder.append('-');
            viewBuilder.append(splits[1]);
            viewBuilder.append('-');
            viewBuilder.append(splits[2]);
            viewBuilder.append(splits[3]);
            String viewName = viewBuilder.toString();
            if (viewDefs.containsKey(viewName)) {
                String viewDef = viewDefs.get(viewName);
                int pos = viewDef.indexOf("FROM");
                String subView = viewDef.substring(pos + 4);
                // String[] viewSources = subView.split("\\.");
                String[] viewSources = subView.split("(\\.\"|\")");
                if (!viewSources[0].equalsIgnoreCase(schemaName)) {
                    createOrReplaceView(connection, schemaName, tableName, viewName, ownerName);
                }
            } else {
                createOrReplaceView(connection, schemaName, tableName, viewName, ownerName);
            }
 
        } else {
 
            splits = tableName.split("_");
            if (splits.length > 0) {
                StringBuilder viewBuilder = new StringBuilder();
                viewBuilder.append(splits[0]);
                if (splits.length > 1) viewBuilder.append(splits[1]);
                if (splits.length > 2) viewBuilder.append(splits[2]);
                String viewName = viewBuilder.toString();
                if (viewDefs.containsKey(viewName)) {
                    String viewDef = viewDefs.get(viewName);
                    int pos = viewDef.indexOf("FROM");
                    String subView = viewDef.substring(pos + 4);
                    String[] viewSources = subView.split("(\\.\"|\")");
                    if (!viewSources[0].equalsIgnoreCase(schemaName)) {
                        createOrReplaceView(connection, schemaName, tableName, viewName, ownerName);
                    }
                } else {
                    createOrReplaceView(connection, schemaName, tableName, viewName, ownerName);
                }
            }
        }
    }
 
    private void resetExtraPostgisDataView(Connection connection, String ownerName, String currentSchema,
                                           ArrayList<String> realTableNames) {
        try {
            // ArrayList<String> extraViewNames = new ArrayList<String>();
            XGeosDataConfigMapping configMapping = getConfigMapping();
            MultiMap configMultiMap = configMapping.getMapping();
            logger.warn("configMapping:"+configMapping.getMapping().keySet().toString());
            for (Object key : configMultiMap.keySet()) {
                List values = (List) configMultiMap.get(key);
                for (Object value : values) {
                    XGeosDataConfig xgeosConfig = (XGeosDataConfig) value;
                    short tid = xgeosConfig.getFSC();
                    short cid = xgeosConfig.getCOMP();
                    StringBuilder sbTable = new StringBuilder("fsc-");
                    sbTable.append(tid).append("-c-");
                    sbTable.append(cid);
                    int index = realTableNames.indexOf(sbTable.toString());
                    if (index == -1) {
                        logger.debug("Cannot found-" + xgeosConfig.toString());
                        continue;
                    }
                    StringBuilder sbView = new StringBuilder("fsc-");
                    sbView.append(tid).append("-c");
                    sbView.append(cid).append("-l");
                    sbView.append(xgeosConfig.getLEV()).append("-w");
                    sbView.append(xgeosConfig.getWEIGHT());
                    // extraViewNames.add(sbView.toString());
 
                    createOrReplaceExtraView(connection, currentSchema, sbTable.toString(), sbView.toString(),
                            ownerName, xgeosConfig);
                }
            }
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
        }
    }
 
    private void resetThemesBaseView(Connection connection, String ownerName, String currentThemesName)
            throws SQLException {
        String viewName = "xpwtheme" + FDYNCOLOR_SUFFIX;
        String tableName = currentThemesName + FDYNCOLOR_SUFFIX;
        PrintfFormat pf = new PrintfFormat("CREATE OR REPLACE VIEW \"%s\" AS SELECT * FROM \"%s\"");
        String sql = pf.sprintf(new Object[]{viewName, tableName});
        Statement stmt = connection.createStatement();
        try {
            stmt.execute(sql);
            pf = new PrintfFormat(ALTER_VIEWSQL + ownerName);
            sql = pf.sprintf(viewName);
            stmt.execute(sql);
 
            viewName = "xpwtheme" + FOWNER_SUFFIX;
            tableName = currentThemesName + FOWNER_SUFFIX;
            pf = new PrintfFormat("CREATE OR REPLACE VIEW \"%s\" AS SELECT * FROM \"%s\"");
            sql = pf.sprintf(new Object[]{viewName, tableName});
 
            stmt.execute(sql);
            pf = new PrintfFormat(ALTER_VIEWSQL + ownerName);
            sql = pf.sprintf(viewName);
            stmt.execute(sql);
        } catch (SQLException e) {
            // logger.warn(e.getMessage(), e);
            logger.info(sql == null ? "SQL=NULL" : "SQL=" + sql);
            throw e;
        } finally {
            stmt.close();
        }
    }
 
 
    private void resetThemesPostgisDataView(Connection connection, String ownerName,
                                            String currentSchema, String viewName) throws SQLException {
        String themeViewName = viewName + "-oms";
        // PrintfFormat pf = new PrintfFormat(CREATE_VIEWSQL);
        // String sql = pf.sprintf(new Object[]{viewName, schemaName, tableName});
        ResultSet rs = null;
        Statement stmt = connection.createStatement();
 
        try {
            StringBuilder sbSQL = new StringBuilder("CREATE OR REPLACE VIEW \"");
            sbSQL.append(themeViewName).append("\" AS SELECT ");
 
            rs = connection.getMetaData().getColumns(null, currentSchema, viewName, "%");
            while (rs.next()) {
                String fieldName = rs.getString("COLUMN_NAME");
                sbSQL.append("t." + fieldName).append(", ");
            }
            sbSQL.append("fc.dyncolor, fo.fowner FROM ");
            if (currentSchema != null)
                sbSQL.append("\"").append(currentSchema).append("\".\"").append(viewName).append("\" AS t,");
            else
                sbSQL.append("\"").append(viewName).append("\" AS t,");
            sbSQL.append("xpwtheme").append(FDYNCOLOR_SUFFIX).append(" AS fc,");
            sbSQL.append("xpwtheme").append(FOWNER_SUFFIX).append(" AS fo WHERE ");
            sbSQL.append("t.tid = fc.tid AND t.oid = fc.oid AND ");
            sbSQL.append("t.tid = fo.tid AND t.oid = fo.oid");
 
            // sbSQL.delete(sbSQL.length() - 2, sbSQL.length());
            String sql = sbSQL.toString();
            stmt.execute(sql);
            sbSQL.delete(0, sbSQL.length());
 
            PrintfFormat pf = new PrintfFormat(ALTER_VIEWSQL + ownerName);
            sql = pf.sprintf(themeViewName);
            stmt.execute(sql);
        } finally {
            JDBCUtils.close(rs);
            JDBCUtils.close(stmt);
        }
    }
 
    private void resetFlowThemesPostgisDataView(Connection connection, String ownerName,
                                            String currentSchema, String viewName) throws SQLException {
        String themeViewName = viewName + "-flow-oms";
        ResultSet rs = null;
        Statement stmt = connection.createStatement();
 
        try {
            StringBuilder sbSQL = new StringBuilder("CREATE OR REPLACE VIEW \"");
            sbSQL.append(themeViewName).append("\" AS SELECT ");
 
            rs = connection.getMetaData().getColumns(null, currentSchema, viewName, "%");
            while (rs.next()) {
                String fieldName = rs.getString("COLUMN_NAME");
                sbSQL.append("t." + fieldName).append(", ");
            }
            sbSQL.append("fc.dyncolor, fo.fowner, fo.flow FROM ");
            if (currentSchema != null)
                sbSQL.append("\"").append(currentSchema).append("\".\"").append(viewName).append("\" AS t,");
            else
                sbSQL.append("\"").append(viewName).append("\" AS t,");
            sbSQL.append("xpwtheme").append(FDYNCOLOR_SUFFIX).append(" AS fc,");
            sbSQL.append("xpwtheme").append(FOWNER_SUFFIX).append(" AS fo WHERE ");
            sbSQL.append("t.tid = fc.tid AND t.oid = fc.oid AND ");
            sbSQL.append("t.tid = fo.tid AND t.oid = fo.oid");
 
            // sbSQL.delete(sbSQL.length() - 2, sbSQL.length());
            String sql = sbSQL.toString();
            stmt.execute(sql);
            sbSQL.delete(0, sbSQL.length());
 
            PrintfFormat pf = new PrintfFormat(ALTER_VIEWSQL + ownerName);
            sql = pf.sprintf(themeViewName);
            stmt.execute(sql);
        } finally {
            JDBCUtils.close(rs);
            JDBCUtils.close(stmt);
        }
    }
 
    private HashMap<String, String> retrieveViewDef(Connection connection, String schemaName, String tablePattern) throws SQLException {
        PreparedStatement stmt = connection.prepareStatement(QUERY_VIEWDEFSQL + "'" + tablePattern + "'");
        stmt.setString(1, schemaName);
        // stmt.setString(2, tablePattern);
        HashMap<String, String> result = new HashMap<String, String>();
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            String tableName = rs.getString(1);
            String viewDef = rs.getString(2);
            result.put(tableName, viewDef);
        }
        rs.close();
        stmt.close();
        return result;
    }
 
    private void createOrReplaceView(Connection connection, String schemaName, String tableName, String viewName,
                                     String ownerName) throws SQLException {
        PrintfFormat pf = new PrintfFormat(CREATE_VIEWSQL);
        String sql = pf.sprintf(new Object[]{viewName, schemaName, tableName});
        Statement stmt = connection.createStatement();
        try {
            stmt.execute(sql);
            pf = new PrintfFormat(ALTER_VIEWSQL + ownerName);
            sql = pf.sprintf(viewName);
            stmt.execute(sql);
        } catch (SQLException e) {
            // logger.warn(e.getMessage(), e);
            logger.info(sql == null ? "SQL=NULL" : "SQL=" + sql);
            throw e;
        } finally {
            stmt.close();
        }
        // connection.commit();
    }
 
    private void createOrReplaceExtraView(Connection connection, String schemaName, String tableName, String viewName,
                                          String ownerName, XGeosDataConfig xgeosConfig) throws SQLException {
        PrintfFormat pf = new PrintfFormat(CREATE_VIEWSQL);
        String sql = pf.sprintf(new Object[]{viewName, schemaName, tableName});
 
        PrintfFormat pfWhere = new PrintfFormat(EXTRAWHERE_VIEWSQL);
        sql += pfWhere.sprintf(new String[]{tableName, Short.toString(xgeosConfig.getLEV()),
                tableName, Short.toString(xgeosConfig.getWEIGHT())});
 
        Statement stmt = connection.createStatement();
        stmt.execute(sql);
 
        pf = new PrintfFormat(ALTER_VIEWSQL + ownerName);
        sql = pf.sprintf(viewName);
        stmt.execute(sql);
        stmt.close();
        // connection.commit();
    }
 
    private Timestamp retrieveCurrentSchemaTimestamp(Connection connection, short status) throws SQLException {
        StringBuilder sbSQL = new StringBuilder("SELECT vstimestamp, vsschema, vsstatus FROM ");
        sbSQL.append(DataReposVersionManager.XGVERSIONTABLE_NAME);
        sbSQL.append(" WHERE vsstatus = ");
        sbSQL.append(status);
        sbSQL.append(" ORDER BY vsid");
 
        Timestamp result = null;
        Statement stmt = null;
        ResultSet rs = null;
 
        try {
            stmt = connection.createStatement();
            rs = stmt.executeQuery(sbSQL.toString());
            // get first result
            if (rs.next()) {
                result = rs.getTimestamp(1);
            }
            return result;
        } finally {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
        }
    }
 
    private void updateCurrentRepositoryStatus(Connection connection, String schemaName, short newStatus)
            throws SQLException {
        StringBuilder sbSQL = new StringBuilder("UPDATE ");
        sbSQL.append(DataReposVersionManager.XGVERSIONTABLE_NAME).append(' ');
        sbSQL.append(" SET vsstatus = ");
        sbSQL.append(newStatus);
        sbSQL.append(", vstimestamp = CURRENT_TIMESTAMP WHERE vsschema = '");
        sbSQL.append(schemaName).append("'");
 
        Statement stmt = null;
        try {
            stmt = connection.createStatement();
            stmt.executeUpdate(sbSQL.toString());
        } finally {
            if (stmt != null) stmt.close();
        }
    }
 
    private boolean checkCurrentRepositoryStatus(Connection connection, short status) {
        try {
            return (retrieveCurrentSchemaName(connection, status) != null);
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    }
 
    private String retrieveCurrentSchemaName(Connection connection, short status) throws SQLException {
        StringBuilder sbSQL = new StringBuilder("SELECT vsschema, vstimestamp, vsstatus FROM ");
        sbSQL.append(encodeSchemaTableName(_pgSchema, DataReposVersionManager.XGVERSIONTABLE_NAME));
        sbSQL.append(" WHERE vsstatus = ");
        sbSQL.append(status);
        sbSQL.append(" ORDER BY vsid");
 
        String result = null;
        Statement stmt = null;
        ResultSet rs = null;
 
        try {
            stmt = connection.createStatement();
            rs = stmt.executeQuery(sbSQL.toString());
            // get first result
            if (rs.next()) {
                result = rs.getString(1);
            }
            return result;
        } finally {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
        }
    }
 
    private void updateCurrentThemeStatus(Connection connection, String themeTableName, short newStatus)
            throws SQLException {
        StringBuilder sbSQL = new StringBuilder("UPDATE ");
        sbSQL.append(DataReposVersionManager.XPTVERSIONTABLE_NAME).append(' ');
        sbSQL.append(" SET vptstatus = ");
        sbSQL.append(newStatus);
        sbSQL.append(", vpttimestamp = CURRENT_TIMESTAMP WHERE vptname = '");
        sbSQL.append(themeTableName).append("'");
 
        Statement stmt = null;
        try {
            stmt = connection.createStatement();
            stmt.executeUpdate(sbSQL.toString());
        } finally {
            if (stmt != null) stmt.close();
        }
    }
 
 
    private boolean checkCurrentThemeStatus(Connection connection, short status) {
        try {
            return (retrieveCurrentThemeName(connection, status) != null);
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
            return false;
        }
    }
 
 
    private String retrieveCurrentThemeName(Connection connection, short status) throws SQLException {
        StringBuilder sbSQL = new StringBuilder("SELECT ");
        sbSQL.append("vptname, vpttimestamp, vptstatus FROM ");
        sbSQL.append(encodeSchemaTableName(_pgSchema, DataReposVersionManager.XPTVERSIONTABLE_NAME));
        sbSQL.append(" WHERE vptstatus = ");
        sbSQL.append(status);
        sbSQL.append("ORDER BY vptid");
 
        String result = null;
        Statement stmt = null;
        ResultSet rs = null;
 
        try {
            stmt = connection.createStatement();
            rs = stmt.executeQuery(sbSQL.toString());
            // get first result
            if (rs.next()) {
                result = rs.getString(1);
            }
            return result;
        } finally {
            JDBCUtils.close(rs);
            JDBCUtils.close(stmt);
        }
    }
 
    protected void transferXGeosVersionStatus(Connection connection,
                                       short vsstatusBefore, short vsstatusAfter, boolean exclusive) throws JobExecutionException {
 
        try {
            String currentTargetSchema = retrieveCurrentSchemaName(connection, vsstatusBefore);
            if (currentTargetSchema == null) {
                logger.info("Cannot found target schema in dataStore. status=" + vsstatusBefore);
                return;
            }
            String existTargetSchema = null;
            if (exclusive)
                existTargetSchema = retrieveCurrentSchemaName(connection, vsstatusAfter);
 
 
            updateCurrentRepositoryStatus(connection, currentTargetSchema, vsstatusAfter);
            if ((exclusive) && (existTargetSchema != null)) {
                updateCurrentRepositoryStatus(connection, existTargetSchema,
                    DataReposVersionManager.VSSTATUS_AVAILABLE);
            }
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
            throw new JobExecutionException("Update " + DataReposVersionManager.XGVERSIONTABLE_NAME +
                " has error-", e);
        }
    }
 
    protected void transferThemesVersionStatus(Connection connection,
                                       short vsstatusBefore, short vsstatusAfter, boolean exclusive) throws JobExecutionException {
 
        try {
            String currentTargetTheme = retrieveCurrentThemeName(connection, vsstatusBefore);
            if (currentTargetTheme == null) {
                logger.info("Cannot found target schema in dataStore. status=" + vsstatusBefore);
                return;
            }
            String existTargetSchema = null;
            if (exclusive)
                existTargetSchema = retrieveCurrentThemeName(connection, vsstatusAfter);
 
 
            updateCurrentThemeStatus(connection, currentTargetTheme, vsstatusAfter);
            if ((exclusive) && (existTargetSchema != null)) {
                updateCurrentThemeStatus(connection, existTargetSchema,
                    DataReposVersionManager.VSSTATUS_AVAILABLE);
            }
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
            throw new JobExecutionException("Update " + DataReposVersionManager.XPTVERSIONTABLE_NAME +
                " has error-", e);
        }
    }
 
    private HashMap<String, String> buildDefaultStylesMapping(XGeosDataConfigMapping configMapping) {
        HashMap<String, String> result = new HashMap<String, String>();
 
        for (Object key : configMapping.getMapping().keySet()) {
            List xgeosConfigs = (List) configMapping.getMapping().get(key);
            for (Object value : xgeosConfigs) {
                XGeosDataConfig xgeosConfig = (XGeosDataConfig) value;
 
                StringBuilder sbView = new StringBuilder("fsc-");
                sbView.append(xgeosConfig.getFSC()).append("-c");
                sbView.append(xgeosConfig.getCOMP()).append("-l");
                sbView.append(xgeosConfig.getLEV()).append("-w");
                sbView.append(xgeosConfig.getWEIGHT());
 
                String viewName = sbView.toString();
                if (!result.containsKey(viewName)) {
                    result.put(viewName, xgeosConfig.getFTYPE());
                } else {
                    if (xgeosConfig.getFTYPE() != null) {
                        if (!result.get(viewName).equals(xgeosConfig.getFTYPE()))
                            logger.info("Style Define Diff:" + result.get(viewName) + " - " + xgeosConfig.getFTYPE());
                    } else {
                        logger.warn("xgeosConfig getFTYPE() is null - " + xgeosConfig.toString());
                    }
                }
            }
        }
        return result;
    }
 
    protected String[] retrieveTargetStoreAllViewNames(Connection connection) {
        try {
            final int TABLE_NAME_COL = 3;
            List list = new ArrayList();
 
            DatabaseMetaData meta = connection.getMetaData();
            // String[] tableType = { "TABLE", "VIEW" };
            String[] tableType = { "VIEW" };
            ResultSet tables = meta.getTables(null, _pgSchema, "%", tableType);
 
            while (tables.next()) {
                String tableName = tables.getString(TABLE_NAME_COL);
                list.add(tableName);
                /*
                if (allowTable(tableName)) {
                    list.add(tableName);
                }
                */
            }
            tables.close();
            return (String[]) list.toArray(new String[list.size()]);
        } catch (SQLException e) {
            logger.warn(e.getMessage(), e);
        }
        return null;
    }
 
    protected String getDefaultFeatureTypeStyleId(Set<String> styles, HashMap<String, String> defaultStyles, FeatureType featureType) {
        String ftName = featureType.getName().getLocalPart();
        boolean isNormalFeature = false;
        boolean isLandBased = false;
        boolean isIndex = false;
        boolean isSmallIndex = false;
        boolean isSymbol = false;
        GeometryDescriptor geomAttrType = featureType.getGeometryDescriptor();
        Class geomType = geomAttrType.getType().getBinding();
        if (defaultStyles.containsKey(ftName)) {
            String defaultStyleName = defaultStyles.get(ftName);
            String styleName = retrieveDefaultStyle(styles, defaultStyleName, "unknown");
            if (!styleName.equals("unknown")) {
                return styleName;
            }
        }
 
        if (ftName.indexOf("fsc") != -1) {
            isNormalFeature = true;
        }
        if (ftName.indexOf("indexshape") != -1) {
            isIndex = true;
        }
        if (ftName.indexOf("indexshapes") != -1) {
            isSmallIndex = true;
        }
        if (ftName.indexOf("lnd") != -1) {
            isLandBased = true;
        }
        if (featureType.getDescriptor("symbol") != null) {
            isSymbol = true;
        }
 
        if (Point.class.equals(geomType)) {
            if (isSymbol) {
                return retrieveDefaultStyle(styles, "xtpc-symbol", "point");
            } else if (isIndex) {
                return retrieveDefaultStyle(styles, "xtpc-text2", "point");
            } else {
                return retrieveDefaultStyle(styles, "xtpc-text", "point");
            }
        } else if (LineString.class.equals(geomType)) {
            if ((!isIndex) && (!isLandBased)) {
                return retrieveDefaultStyle(styles, "xtpc-conductor", "line");
            } else if (isIndex) {
                if (isSmallIndex)
                    return retrieveDefaultStyle(styles, "xtpc-indexshapes", "line");
 
                return retrieveDefaultStyle(styles, "xtpc-indexshape", "line");
            } else if (isLandBased) {
                return retrieveDefaultStyle(styles, "xtpc-lndcityLine", "line");
            }
        } else if (MultiPoint.class.equals(geomType)) {
            if (isSymbol) {
                return retrieveDefaultStyle(styles, "xtpc-symbol", "point");
            } else {
                return retrieveDefaultStyle(styles, "xtpc-text", "point");
            }
        } else if (Polygon.class.equals(geomType)) {
            if (isSymbol) {
                return retrieveDefaultStyle(styles, "xtpc-symbol", "polygon");
            } else if ((!isIndex) && (!isLandBased)) {
                return retrieveDefaultStyle(styles, "polygon", "polygon");
            } else if (isIndex) {
                return retrieveDefaultStyle(styles, "xtpc-indexshape", "polygon");
            } else if (isLandBased) {
                return retrieveDefaultStyle(styles, "xtpc-lndcityPolygon", "polygon");
            }
        } else if (LinearRing.class.equals(geomType)) {
            if (!isIndex) {
                return retrieveDefaultStyle(styles, "polygon", "polygon");
            } else {
                return retrieveDefaultStyle(styles, "xtpc-indexshape", "polygon");
            }
        } else if (MultiLineString.class.equals(geomType)) {
            if ((!isIndex) && (!isLandBased)) {
                return retrieveDefaultStyle(styles, "xtpc-conductor", "line");
            } else if (isLandBased) {
                return retrieveDefaultStyle(styles, "xtpc-lndcityLine", "line");
            } else {
                return retrieveDefaultStyle(styles, "xtpc-indexshape", "line");
            }
        } else if (MultiPolygon.class.equals(geomType)) {
            return "polygon";
        }
 
        return "xtpc-symbol";
    }
 
    private static String retrieveDefaultStyle(Set styles, String styleName, String defaultStyleName) {
        if (styles.contains(styleName)) {
            return styleName;
        } else
            return defaultStyleName;
    }
}