Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.fmap.dal / org.gvsig.fmap.dal.db / org.gvsig.fmap.dal.db.jdbc / src / test / java / org / gvsig / fmap / dal / store / jdbc2 / AbstractTestUtils.java @ 46507

History | View | Annotate | Download (22 KB)

1
package org.gvsig.fmap.dal.store.jdbc2;
2

    
3
import java.io.File;
4
import java.net.URL;
5
import java.util.ArrayList;
6
import java.util.HashMap;
7
import java.util.List;
8
import java.util.Map;
9
import java.util.Properties;
10
import org.apache.commons.collections4.CollectionUtils;
11
import org.apache.commons.io.FileUtils;
12
import org.apache.commons.io.FilenameUtils;
13
import org.apache.commons.io.IOUtils;
14
import org.apache.commons.lang3.BooleanUtils;
15
import org.apache.commons.lang3.StringUtils;
16
import org.apache.commons.lang3.math.NumberUtils;
17
import org.gvsig.expressionevaluator.ExpressionUtils;
18
import org.gvsig.fmap.dal.DALLocator;
19
import org.gvsig.fmap.dal.DataManager;
20
import org.gvsig.fmap.dal.DataStore;
21
import static org.gvsig.fmap.dal.DataStore.H2SPATIAL_PROVIDER_NAME;
22
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
23
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
24
import org.gvsig.fmap.dal.feature.EditableFeature;
25
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
26
import org.gvsig.fmap.dal.feature.EditableFeatureType;
27
import org.gvsig.fmap.dal.feature.Feature;
28
import org.gvsig.fmap.dal.feature.FeatureQuery;
29
import org.gvsig.fmap.dal.feature.FeatureStore;
30
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
31
import org.gvsig.fmap.dal.feature.impl.DefaultFeature;
32
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
33
import org.gvsig.fmap.dal.impl.expressionevaluator.DefaultFeatureAttributeEmulatorExpression;
34
import org.gvsig.fmap.dal.store.jdbc.JDBCServerExplorerParameters;
35
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
36
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
37
import org.gvsig.tools.util.HasAFile;
38
import org.slf4j.Logger;
39
import org.slf4j.LoggerFactory;
40

    
41
public abstract class AbstractTestUtils {
42

    
43
    public static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestUtils.class);
44

    
45
    protected static int dbcounter = 1;
46

    
47
    protected Properties properties = null;
48

    
49
    public AbstractTestUtils() {
50

    
51
    }
52

    
53
    public File getTargetFolder() throws Exception {
54
        URL url = this.getClass().getResource("/");
55
        if (url == null) {
56
            url = AbstractTestUtils.class.getResource("/");
57
        }
58
        File x = new File(url.toURI());
59
        File target = x.getParentFile();
60
        return target;
61
    }
62

    
63
    public File getResource(String name) throws Exception {
64
        File x = new File(getTargetFolder(), name);
65
        return x;
66
    }
67

    
68
    public File getResourceAsFile(String pathname) throws Exception {
69
        URL url = this.getClass().getResource(pathname);
70
        if (url == null) {
71
            url = AbstractTestUtils.class.getResource(pathname);
72
        }
73
        if( StringUtils.equalsIgnoreCase(url.getProtocol(),"file") ) {
74
            File x = new File(url.toURI());
75
            return x;
76
        }
77
        File tmp = new File( this.getTargetFolder(), FilenameUtils.getName(pathname));
78
        IOUtils.copy(url, tmp);
79
        return tmp;
80
    }
81

    
82
    public File getFile(File name) throws Exception {
83
        File f = this.getResource(String.format(
84
                "%s-%d-%03d",
85
                name.getPath(),
86
                System.currentTimeMillis(),
87
                dbcounter++
88
        )
89
        );
90
        FileUtils.forceMkdir(f.getParentFile());
91
        return f;
92
    }
93

    
94
    public File getFolder(File name) throws Exception {
95
        File f = this.getResource(String.format(
96
                "%s-%d-%03d",
97
                name.getPath(),
98
                System.currentTimeMillis(),
99
                dbcounter++
100
        )
101
        );
102
        FileUtils.forceMkdir(f);
103
        return f;
104
    }
105

    
106
    public JDBCServerExplorerParameters getH2SpatialServerExplorerParameters(String dbname) throws Exception {
107
        DataManager dataManager = DALLocator.getDataManager();
108
        JDBCServerExplorerParameters conn = (JDBCServerExplorerParameters) dataManager.createServerExplorerParameters(H2SPATIAL_PROVIDER_NAME);
109

    
110
        File dbfile = this.getResource(String.format(
111
                "test-dbs/%s-%d-%03d",
112
                dbname,
113
                System.currentTimeMillis(),
114
                dbcounter++
115
        )
116
        );
117
//        System.out.println("#### dbfile: " + dbfile.getAbsolutePath());
118
        FileUtils.forceMkdir(dbfile.getParentFile());
119
        ((HasAFile) conn).setFile(dbfile);
120
        return conn;
121
    }
122

    
123
    public FeatureProvider getFeatureProvider(Feature feature) {
124
        return ((DefaultFeature) feature).getData();
125
    }
126

    
127
    public Expecteds getExpecteds(String name) throws Exception {
128
        Expecteds x = new Expecteds();
129
        x.normaliceSpaces = false;
130
        x.removeNL = true;
131
        x.stripStart = true;
132
        File f = getResourceAsFile(getExpectedsPath() + "/" + name);
133
        x.parse(f);
134
        return x;
135
    }
136

    
137
    public static class Expecteds {
138

    
139
        private Map<String, List<String>> expecteds = new HashMap<>();
140

    
141
        public boolean normaliceSpaces = false;
142
        public boolean stripStart = false;
143
        public boolean removeNL = false;
144
        public boolean replace_nl_by_space = false;
145
        public boolean trim_end = false;
146
        
147

    
148
        public String startLineComment = "-- ";
149
        
150
        private static class CommandLine {
151

    
152
            private final String[] cmd;
153

    
154
            private CommandLine(String line, String prefix) {
155
                line = StringUtils.substring(line, prefix.length());
156
                line = StringUtils.normalizeSpace(line);
157
                this.cmd = StringUtils.split(line);
158
            }
159

    
160
            public boolean isTrue(int argn, boolean defaultValue) {
161
                if (argn >= this.cmd.length) {
162
                    return defaultValue;
163
                }
164
                return BooleanUtils.toBoolean(this.cmd[argn]);
165
            }
166
            
167
            public String get(int argn) {
168
                return this.cmd[argn];
169
            }
170
            
171
            public int size() {
172
                return this.cmd.length;
173
            }
174
        }
175

    
176
        public Expecteds() throws Exception {
177
            
178
        }
179
        
180
        public void parse(File f) throws Exception {
181
            final int SEARCHING_ITEM = 0;
182
            final int READING_ITEM = 1;
183
            boolean localNormaliceSpaces = false;
184
            boolean localStripStart = false;
185
            boolean localRemoveNL = false;
186
            boolean local_replace_nl_by_space = false;
187
            boolean local_trim_end = false;
188
            String name = f.getName();
189

    
190
            List<String> lines = FileUtils.readLines(f);
191

    
192
            StringBuilder sb = null;
193
            String currentItem = null;
194
            int lineno = 1;
195
            int state = SEARCHING_ITEM;
196
            for (String line : lines) {
197
                line = line + "\n";
198
                switch (state) {
199
                    case SEARCHING_ITEM:
200
                        if (line.toLowerCase().startsWith(startLineComment + "normalize-spaces")) {
201
                            CommandLine cmd = new CommandLine(line, startLineComment);
202
                            normaliceSpaces = cmd.isTrue(1, true);
203
                        } else if (line.toLowerCase().startsWith(startLineComment + "strip-start")) {
204
                            CommandLine cmd = new CommandLine(line, startLineComment);
205
                            stripStart = cmd.isTrue(1, true);
206
                        } else if (line.toLowerCase().startsWith(startLineComment + "remove-nl")) {
207
                            CommandLine cmd = new CommandLine(line, startLineComment);
208
                            removeNL = cmd.isTrue(1, true);
209
                        } else if (line.toLowerCase().startsWith(startLineComment + "replace-nl-by-space")) {
210
                            CommandLine cmd = new CommandLine(line, startLineComment);
211
                            replace_nl_by_space = cmd.isTrue(1, true);
212
                        } else if (line.toLowerCase().startsWith(startLineComment + "trim-end")) {
213
                            CommandLine cmd = new CommandLine(line, startLineComment);
214
                            trim_end = cmd.isTrue(1, true);
215
                        } else if (line.toLowerCase().startsWith(startLineComment + "begin ")) {
216
                            CommandLine cmd = new CommandLine(line, startLineComment);
217
                            currentItem = cmd.get(1);
218
                            sb = new StringBuilder();
219
                            state = READING_ITEM;
220
                            localNormaliceSpaces = normaliceSpaces;
221
                            localStripStart = stripStart;
222
                            localRemoveNL = removeNL;
223
                            local_replace_nl_by_space = replace_nl_by_space;
224
                            local_trim_end = trim_end;
225
                        } else if (line.toLowerCase().startsWith(startLineComment + "rem ")) {
226
                            // do nothing skip comment
227
                        } else if (!StringUtils.isBlank(line)) {
228
                            throw new IllegalStateException("Syntax error at '" + name + "', line " + lineno + ".");
229
                        }
230
                        break;
231
                    case READING_ITEM:
232
                        if (line.toLowerCase().startsWith(startLineComment + "normalize-spaces")) {
233
                            CommandLine cmd = new CommandLine(line, startLineComment);
234
                            localNormaliceSpaces = cmd.isTrue(1, true);
235
                        } else if (line.toLowerCase().startsWith(startLineComment + "strip-start")) {
236
                            CommandLine cmd = new CommandLine(line, startLineComment);
237
                            localStripStart = cmd.isTrue(1, true);
238
                        } else if (line.toLowerCase().startsWith(startLineComment + "remove-nl")) {
239
                            CommandLine cmd = new CommandLine(line, startLineComment);
240
                            localRemoveNL = cmd.isTrue(1, true);
241
                        } else if (line.toLowerCase().startsWith(startLineComment + "replace-nl-by-space")) {
242
                            CommandLine cmd = new CommandLine(line, startLineComment);
243
                            local_replace_nl_by_space = cmd.isTrue(1, true);
244
                        } else if (line.toLowerCase().startsWith(startLineComment + "trim-end")) {
245
                            CommandLine cmd = new CommandLine(line, startLineComment);
246
                            local_trim_end = cmd.isTrue(1, true);
247
                        } else if (line.toLowerCase().startsWith(startLineComment + "end ")) {
248
                            CommandLine cmd = new CommandLine(line, startLineComment);
249
                            if (!StringUtils.equals(currentItem, cmd.get(1)) )  {
250
                                throw new IllegalStateException("Syntax error at '" + name + "', line " + lineno + ", expected '" + startLineComment + "end " + currentItem + "', and found " + line + ".");
251
                            }
252
                            String s = sb.toString();
253
                            if (s.endsWith("\n")) {
254
                                s = s.substring(0, s.length() - 1);
255
                            }
256
                            if (localNormaliceSpaces) {
257
                                s = StringUtils.normalizeSpace(s);
258
                            }
259
                            if( local_trim_end ) {
260
                                s = StringUtils.stripEnd(s, " ");
261
                            }
262
                            
263
                            List<String> value = expecteds.get(currentItem);
264
                            if( value == null ) {
265
                                value = new ArrayList<>();
266
                                expecteds.put(currentItem, value);
267
                            }
268
                            value.add(s);
269
                            state = SEARCHING_ITEM;
270

    
271
                        } else if (line.toLowerCase().startsWith(startLineComment + "rem ")) {
272
                            // do nothing skip comment
273
                        } else {
274
                            if (localStripStart) {
275
                                line = StringUtils.stripStart(line, null);
276
                            }
277
                            if( local_replace_nl_by_space ) {
278
                                line = line.replace('\n', ' ');
279
                            }
280
                            if (localRemoveNL) {
281
                                line = StringUtils.remove(line, "\n");
282
                                line = StringUtils.remove(line, "\r");
283
                            }
284
                            sb.append(line);
285
                        }
286
                        break;
287
                }
288
                lineno++;
289
            }
290
            if (state != SEARCHING_ITEM) {
291
                throw new IllegalStateException("Syntax error at '" + name + "', expected '" + startLineComment + "end " + currentItem + "' and found EOF .");
292
            }
293
        }
294

    
295
        public String get(String name) {
296
            List<String> value = this.expecteds.get(name);
297
            if( CollectionUtils.isEmpty(value) ) {
298
                return null;
299
            }
300
            return value.get(0);
301
        }
302

    
303
        public String get(String name, int index) {
304
            List<String> value = this.expecteds.get(name);
305
            if( CollectionUtils.isEmpty(value) ) {
306
                return null;
307
            }
308
            return value.get(index);
309
        }
310
        
311
        public int size(String name) {
312
            List<String> value = this.expecteds.get(name);
313
            if( CollectionUtils.isEmpty(value) ) {
314
                return 0;
315
            }
316
            return value.size();
317
        }
318
    }
319

    
320
    public void removeResource(JDBCServerExplorer explorer, String storeName, String resourceName) throws Exception {
321
        JDBCStoreParameters storeParams = explorer.get(storeName);
322
        ResourcesStorage resourcesStorage = explorer.getResourcesStorage(storeParams);
323
        if( resourcesStorage.allowRemove() ) {
324
            resourcesStorage.remove(resourceName);
325
        }
326
    }
327

    
328
    public void info_h2sql(String label, File file) {
329
        System.out.println("");
330
        System.out.println("#h2console "+label+": "+file.getName());
331
        System.out.println("cd '"+file.getParent()+"'; h2sql -d '"+file.getName()+"' -user SA");
332
        System.out.println("jdbc:h2:"+file.getAbsolutePath()+";MODE=PostgreSQL;SCHEMA=PUBLIC;ALLOW_LITERALS=ALL");
333
        System.out.println("jdbc:h2:tcp://127.0.1.1:9123/"+file.getAbsolutePath()+";MODE=PostgreSQL;SCHEMA=PUBLIC;ALLOW_LITERALS=ALL");
334
        System.out.println("");
335
    }
336
    
337
    public void info_jdbc(String label, JDBCServerExplorerParameters parameters) {
338
        if( StringUtils.equalsIgnoreCase(parameters.getProviderName(), FeatureStore.H2SPATIAL_PROVIDER_NAME) ) {
339
            info_h2sql(label, ((HasAFile)parameters).getFile());
340
            return;
341
        }
342
        System.out.println("");
343
        System.out.println("# Connection "+label);
344
        System.out.println(parameters.getUrl());
345
        System.out.println("");
346
    }
347
    
348
    public void info_jdbc(String label, JDBCServerExplorer explorer) {
349
        info_jdbc(label, explorer.getParameters());
350
    }
351
    
352
    public void info_jdbc(JDBCServerExplorer explorer) {
353
        JDBCServerExplorerParameters params = explorer.getParameters();
354
        info_jdbc(params.getDBName(), params);
355
    }
356
    
357
    protected boolean getPropertyBoolean(String name) {
358
        Properties props = this.getProperties();
359
        return BooleanUtils.toBoolean(props.getProperty(name));
360
    }
361
    
362
    protected int getPropertyInt(String name, int defaultValue) {
363
        Properties props = this.getProperties();
364
        return NumberUtils.toInt(props.getProperty(name), defaultValue);
365
    }
366
    
367
    protected String getProperty(String name) {
368
        Properties props = this.getProperties();
369
        return props.getProperty(name);
370
    }
371
    
372
    protected Properties getProperties() {
373
        if( this.properties == null ) {
374
            try {
375
                Properties props = new Properties();
376
                this.properties = props;
377
            } catch(Exception ex) {
378
                throw new RuntimeException(ex);
379
            }
380
        }
381
        return this.properties;
382
    }
383

    
384
    public boolean isTheDatabaseAvailable() {
385
        return true;
386
    }
387

    
388
    public FeatureStore openCSVStore(String pathname) throws Exception {
389
        DataManager dataManager = DALLocator.getDataManager();
390
        File f = getResourceAsFile(pathname);
391
        FeatureStore store = (FeatureStore) dataManager.openStore(
392
                DataStore.CSV_PROVIDER_NAME, 
393
                "file=",f,
394
                "automaticTypesDetection=", false,
395
                "locale=","en"
396
        );
397
        return store;
398
    }
399
    
400
    public FeatureStore openSourceStore1() throws Exception {
401
        return this.openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/testCreateSource1.csv");
402
    }
403

    
404
    public FeatureStore openSourceStore2() throws Exception {
405
        return this.openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/testCreateSource2.csv");
406
    }
407

    
408
    public FeatureStore openStore(JDBCServerExplorer explorer, String name) throws Exception {
409
        JDBCStoreParameters params = explorer.get(name);
410
        
411
        DataManager dataManager = DALLocator.getDataManager();
412
        FeatureStore store;
413
        try {
414
            store = (FeatureStore) dataManager.openStore(
415
                    getProviderName(), 
416
                    params
417
            );
418
        } catch(ValidateDataParametersException ex) {
419
            LOGGER.warn(ex.getLocalizedMessageStack());
420
            throw ex;
421
        }
422
        return store;
423
    }
424

    
425
    public void create_table_from(JDBCServerExplorer targetExplorer, String targetName, FeatureStore sourceStore) throws Exception {
426
        NewFeatureStoreParameters params = (NewFeatureStoreParameters) targetExplorer.getAddParameters(
427
                targetName
428
        );
429
        EditableFeatureType ft = params.getDefaultFeatureType();
430
        ft.addAll(sourceStore.getDefaultFeatureType());
431
        targetExplorer.add(getProviderName(), params, true);
432
    }
433
    
434
    public void insert_into_from(JDBCServerExplorer targetExplorer, String targetName, FeatureStore sourceStore, int mode) throws Exception {
435
        FeatureStore targetStore = openStore(targetExplorer, targetName);
436
        targetStore.edit(mode);
437
        try {
438
            for (Feature sourceFeature : sourceStore.getFeatureSet()) {
439
                EditableFeature targetFeature = targetStore.createNewFeature(sourceFeature);
440
                targetStore.insert(targetFeature);
441
            }
442
        } finally {
443
            targetStore.finishEditing();
444
        }
445
    }
446
    
447
    public JDBCServerExplorer openServerExplorer(String dbname) throws Exception {        
448
        DataManager dataManager = DALLocator.getDataManager();
449
        JDBCServerExplorerParameters params = this.getServerExplorerParameters(dbname);
450
        JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
451
                this.getProviderName(), 
452
                params
453
        );
454
        return explorer;
455
    }
456

    
457
    public void drop_tables(JDBCServerExplorer explorer, String...tables) throws Exception {
458
        for (String table : tables) {
459
            String sql = "DROP TABLE IF EXISTS \""+table+"\"";
460
            explorer.execute(sql);
461
            removeResource(explorer, table, "dal");
462
        }
463
    }
464
    
465
    public DatabaseWorkspaceManager initWorkspace(String name) throws Exception {
466
        JDBCServerExplorer explorer = this.openServerExplorer(name);
467
        DataManager manager = DALLocator.getDataManager();
468
        DatabaseWorkspaceManager ws = manager.createDatabaseWorkspaceManager(explorer.getParameters());
469
        ws.connect();
470
        if (!ws.existsTable(DatabaseWorkspaceManager.TABLE_CONFIGURATION)) {
471
            ws.createTable(DatabaseWorkspaceManager.TABLE_CONFIGURATION);
472
        }
473
        if (!ws.existsTable(DatabaseWorkspaceManager.TABLE_RESOURCES)) {
474
            ws.createTable(DatabaseWorkspaceManager.TABLE_RESOURCES);
475
        }
476
        return ws;
477
    }
478
    
479
    public List<String> getExpectedSQLs(String name) throws Exception {
480
        File f = getResourceAsFile(getExpectedsPath() + "/" + name);
481
        List<String> SQLs = new ArrayList<>();
482
        List<String> lines = FileUtils.readLines(f);
483
        StringBuilder sb = new StringBuilder();
484
        for (String line : lines) {
485
            line = StringUtils.stripStart(line, null);
486
            if (line.startsWith("--")) {
487
                continue;
488
            }
489
            if (line.endsWith(";")) {
490
                sb.append(line.substring(0, line.length() - 1));
491
                SQLs.add(sb.toString());
492
                sb.setLength(0);
493
            } else {
494
                sb.append(line);
495
            }
496
        }
497
        return SQLs;
498
    }
499

    
500
    
501
//    public abstract String getExpectedResourcesPrefix(); // Ex. "h2spatial"
502

    
503
    public abstract String getExpectedsPath();
504
    
505
    public abstract JDBCHelper createJDBCHelper() throws Exception;
506

    
507
    public abstract String getProviderName();
508
    
509
    public abstract JDBCServerExplorerParameters getServerExplorerParameters(String dbname) throws Exception;
510

    
511
    public void runSQLToCheckSyntax(String testName, FeatureStore datacsv, String testTableName, String sql) throws Exception {
512
        JDBCServerExplorer explorer = this.openServerExplorer(testName);
513

    
514
        this.info_jdbc(explorer);
515
        this.drop_tables(explorer, testTableName);
516

    
517
        this.create_table_from(explorer, testTableName, datacsv);
518
        this.insert_into_from(explorer, testTableName, datacsv, FeatureStore.MODE_APPEND);
519

    
520
        explorer.execute(sql);
521
    }
522
    
523
    public void output_results(String testName, String sqlresult, String sqlexpected) {
524
        System.out.println("###### "+testName+"()");
525
        System.out.println("###### SQL:" + sqlresult+";");
526
        System.out.println("###### EXP:" + sqlexpected+";");
527
    }
528

    
529
    public EditableFeatureAttributeDescriptor addExtraColumn(EditableFeatureType eFeatureType, FeatureQuery query, String name, int type, String exp) {
530
        EditableFeatureAttributeDescriptor extraColumn = query.getExtraColumn().add(name, type);
531
        extraColumn.setFeatureAttributeEmulator(new DefaultFeatureAttributeEmulatorExpression(eFeatureType, ExpressionUtils.createExpression(exp)));
532
        return extraColumn;
533
    }
534

    
535

    
536
}