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 @ 46105

History | View | Annotate | Download (18.2 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.fmap.dal.DALLocator;
18
import org.gvsig.fmap.dal.DataManager;
19
import org.gvsig.fmap.dal.DataServerExplorerParameters;
20
import org.gvsig.fmap.dal.DataStore;
21
import static org.gvsig.fmap.dal.DataStore.H2SPATIAL_PROVIDER_NAME;
22
import org.gvsig.fmap.dal.DataStoreParameters;
23
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
24
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.FIELD_RESOURCES_NAME;
25
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_RESOURCES_NAME;
26
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
27
import org.gvsig.fmap.dal.feature.EditableFeature;
28
import org.gvsig.fmap.dal.feature.EditableFeatureType;
29
import org.gvsig.fmap.dal.feature.Feature;
30
import org.gvsig.fmap.dal.feature.FeatureStore;
31
import org.gvsig.fmap.dal.feature.NewFeatureStoreParameters;
32
import org.gvsig.fmap.dal.feature.impl.DefaultFeature;
33
import org.gvsig.fmap.dal.feature.spi.FeatureProvider;
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.hibernate.dialect.H2Dialect;
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41

    
42
public abstract class AbstractTestUtils {
43

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

    
46
    protected static int dbcounter = 1;
47

    
48
    protected Properties properties = null;
49

    
50
    public AbstractTestUtils() {
51

    
52
    }
53

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

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

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

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

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

    
101
    public JDBCServerExplorerParameters getH2SpatialServerExplorerParameters(String dbname) throws Exception {
102
        DataManager dataManager = DALLocator.getDataManager();
103
        JDBCServerExplorerParameters conn = (JDBCServerExplorerParameters) dataManager.createServerExplorerParameters(H2SPATIAL_PROVIDER_NAME);
104

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

    
118
    public FeatureProvider getFeatureProvider(Feature feature) {
119
        return ((DefaultFeature) feature).getData();
120
    }
121

    
122
    public Expecteds getExpecteds(String name) throws Exception {
123
        Expecteds x = new Expecteds();
124
        x.normaliceSpaces = false;
125
        x.removeNL = true;
126
        x.stripStart = true;
127
        File f = getResourceAsFile(getExpectedsPath() + "/" + name);
128
        x.parse(f);
129
        return x;
130
    }
131

    
132
    public static class Expecteds {
133

    
134
        private Map<String, List<String>> expecteds = new HashMap<>();
135

    
136
        public boolean normaliceSpaces = false;
137
        public boolean stripStart = false;
138
        public boolean removeNL = false;
139

    
140
        private static class CommandLine {
141

    
142
            private final String[] cmd;
143

    
144
            private CommandLine(String line, String prefix) {
145
                line = StringUtils.substring(line, prefix.length());
146
                line = StringUtils.normalizeSpace(line);
147
                this.cmd = StringUtils.split(line);
148
            }
149

    
150
            public boolean isTrue(int argn, boolean defaultValue) {
151
                if (argn >= this.cmd.length) {
152
                    return defaultValue;
153
                }
154
                return BooleanUtils.toBoolean(this.cmd[argn]);
155
            }
156
            
157
            public String get(int argn) {
158
                return this.cmd[argn];
159
            }
160
            
161
            public int size() {
162
                return this.cmd.length;
163
            }
164
        }
165

    
166
        public Expecteds() throws Exception {
167
            
168
        }
169
        
170
        public void parse(File f) throws Exception {
171
            final int SEARCHING_ITEM = 0;
172
            final int READING_ITEM = 1;
173
            final String startLineComment = "-- ";
174
            boolean localNormaliceSpaces = false;
175
            boolean localStripStart = false;
176
            boolean localRemoveNL = false;
177
            String name = f.getName();
178

    
179
            List<String> lines = FileUtils.readLines(f);
180

    
181
            StringBuilder sb = null;
182
            String currentItem = null;
183
            int lineno = 1;
184
            int state = SEARCHING_ITEM;
185
            for (String line : lines) {
186
                line = line + "\n";
187
                switch (state) {
188
                    case SEARCHING_ITEM:
189
                        if (line.toLowerCase().startsWith(startLineComment + "normalize-spaces")) {
190
                            CommandLine cmd = new CommandLine(line, startLineComment);
191
                            normaliceSpaces = cmd.isTrue(1, true);
192
                        } else if (line.toLowerCase().startsWith(startLineComment + "strip-start")) {
193
                            CommandLine cmd = new CommandLine(line, startLineComment);
194
                            stripStart = cmd.isTrue(1, true);
195
                        } else if (line.toLowerCase().startsWith(startLineComment + "remove-nl")) {
196
                            CommandLine cmd = new CommandLine(line, startLineComment);
197
                            removeNL = cmd.isTrue(1, true);
198
                        } else if (line.toLowerCase().startsWith(startLineComment + "begin ")) {
199
                            CommandLine cmd = new CommandLine(line, startLineComment);
200
                            currentItem = cmd.get(1);
201
                            sb = new StringBuilder();
202
                            state = READING_ITEM;
203
                            localNormaliceSpaces = normaliceSpaces;
204
                            localStripStart = stripStart;
205
                            localRemoveNL = removeNL;
206
                        } else if (line.toLowerCase().startsWith(startLineComment + "rem ")) {
207
                            // do nothing skip comment
208
                        } else if (!StringUtils.isBlank(line)) {
209
                            throw new IllegalStateException("Syntax error at '" + name + "', line " + lineno + ".");
210
                        }
211
                        break;
212
                    case READING_ITEM:
213
                        if (line.toLowerCase().startsWith(startLineComment + "normalize-spaces")) {
214
                            CommandLine cmd = new CommandLine(line, startLineComment);
215
                            localNormaliceSpaces = cmd.isTrue(1, true);
216
                        } else if (line.toLowerCase().startsWith(startLineComment + "strip-start")) {
217
                            CommandLine cmd = new CommandLine(line, startLineComment);
218
                            localStripStart = cmd.isTrue(1, true);
219
                        } else if (line.toLowerCase().startsWith(startLineComment + "remove-nl")) {
220
                            CommandLine cmd = new CommandLine(line, startLineComment);
221
                            localRemoveNL = cmd.isTrue(1, true);
222
                        } else if (line.toLowerCase().startsWith(startLineComment + "end ")) {
223
                            CommandLine cmd = new CommandLine(line, startLineComment);
224
                            if (!StringUtils.equals(currentItem, cmd.get(1)) )  {
225
                                throw new IllegalStateException("Syntax error at '" + name + "', line " + lineno + ", expected '" + startLineComment + "end " + currentItem + "', and found " + line + ".");
226
                            }
227
                            String s = sb.toString();
228
                            if (s.endsWith("\n")) {
229
                                s = s.substring(0, s.length() - 1);
230
                            }
231
                            if (localNormaliceSpaces) {
232
                                s = StringUtils.normalizeSpace(s);
233
                            }
234
                            
235
                            List<String> value = expecteds.get(currentItem);
236
                            if( value == null ) {
237
                                value = new ArrayList<>();
238
                                expecteds.put(currentItem, value);
239
                            }
240
                            value.add(s);
241
                            state = SEARCHING_ITEM;
242

    
243
                        } else if (line.toLowerCase().startsWith(startLineComment + "rem ")) {
244
                            // do nothing skip comment
245
                        } else {
246
                            if (localStripStart) {
247
                                line = StringUtils.stripStart(line, null);
248
                            }
249
                            if (localRemoveNL) {
250
                                line = StringUtils.remove(line, "\n");
251
                                line = StringUtils.remove(line, "\r");
252
                            }
253
                            sb.append(line);
254
                        }
255
                        break;
256
                }
257
                lineno++;
258
            }
259
            if (state != SEARCHING_ITEM) {
260
                throw new IllegalStateException("Syntax error at '" + name + "', expected '" + startLineComment + "end " + currentItem + "' and found EOF .");
261
            }
262
        }
263

    
264
        public String get(String name) {
265
            List<String> value = this.expecteds.get(name);
266
            if( CollectionUtils.isEmpty(value) ) {
267
                return null;
268
            }
269
            return value.get(0);
270
        }
271

    
272
        public String get(String name, int index) {
273
            List<String> value = this.expecteds.get(name);
274
            if( CollectionUtils.isEmpty(value) ) {
275
                return null;
276
            }
277
            return value.get(index);
278
        }
279
        
280
        public int size(String name) {
281
            List<String> value = this.expecteds.get(name);
282
            if( CollectionUtils.isEmpty(value) ) {
283
                return 0;
284
            }
285
            return value.size();
286
        }
287
    }
288

    
289
    public void removeResource(JDBCServerExplorer explorer, String storeName, String resourceName) throws Exception {
290
        JDBCStoreParameters storeParams = explorer.get(storeName);
291
        ResourcesStorage resourcesStorage = explorer.getResourcesStorage(storeParams);
292
        resourcesStorage.remove(resourceName);
293
    }
294

    
295
    public void info_h2sql(String label, File file) {
296
        System.out.println("");
297
        System.out.println("#h2console "+label+": "+file.getName());
298
        System.out.println("cd '"+file.getParent()+"'; h2sql -d '"+file.getName()+"' -user SA");
299
        System.out.println("jdbc:h2:"+file.getAbsolutePath()+";MODE=PostgreSQL;SCHEMA=PUBLIC;ALLOW_LITERALS=ALL");
300
        System.out.println("jdbc:h2:tcp://127.0.1.1:9123/"+file.getAbsolutePath()+";MODE=PostgreSQL;SCHEMA=PUBLIC;ALLOW_LITERALS=ALL");
301
        System.out.println("");
302
    }
303
    
304
    public void info_jdbc(String label, JDBCServerExplorerParameters parameters) {
305
        if( StringUtils.equalsIgnoreCase(parameters.getProviderName(), FeatureStore.H2SPATIAL_PROVIDER_NAME) ) {
306
            info_h2sql(label, ((HasAFile)parameters).getFile());
307
            return;
308
        }
309
        System.out.println("");
310
        System.out.println("# Connection "+label);
311
        System.out.println(parameters.getUrl());
312
        System.out.println("");
313
    }
314
    
315
    public void info_jdbc(String label, JDBCServerExplorer explorer) {
316
        info_jdbc(label, explorer.getParameters());
317
    }
318
    
319
    public void info_jdbc(JDBCServerExplorer explorer) {
320
        JDBCServerExplorerParameters params = explorer.getParameters();
321
        info_jdbc(params.getDBName(), params);
322
    }
323
    
324
    protected boolean getPropertyBoolean(String name) {
325
        Properties props = this.getProperties();
326
        return BooleanUtils.toBoolean(props.getProperty(name));
327
    }
328
    
329
    protected int getPropertyInt(String name, int defaultValue) {
330
        Properties props = this.getProperties();
331
        return NumberUtils.toInt(props.getProperty(name), defaultValue);
332
    }
333
    
334
    protected String getProperty(String name) {
335
        Properties props = this.getProperties();
336
        return props.getProperty(name);
337
    }
338
    
339
    protected Properties getProperties() {
340
        if( this.properties == null ) {
341
            try {
342
                Properties props = new Properties();
343
                this.properties = props;
344
            } catch(Exception ex) {
345
                throw new RuntimeException(ex);
346
            }
347
        }
348
        return this.properties;
349
    }
350

    
351
    public boolean isTheDatabaseAvailable() {
352
        return true;
353
    }
354

    
355
    public FeatureStore openCSVStore(String pathname) throws Exception {
356
        DataManager dataManager = DALLocator.getDataManager();
357
        File f = getResourceAsFile(pathname);
358
        FeatureStore store = (FeatureStore) dataManager.openStore(
359
                DataStore.CSV_PROVIDER_NAME, 
360
                "file=",f,
361
                "automaticTypesDetection=", false,
362
                "locale=","en"
363
        );
364
        return store;
365
    }
366
    
367
    public FeatureStore openSourceStore1() throws Exception {
368
        return this.openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/testCreateSource1.csv");
369
    }
370

    
371
    public FeatureStore openSourceStore2() throws Exception {
372
        return this.openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/testCreateSource2.csv");
373
    }
374

    
375
    public FeatureStore openStore(JDBCServerExplorer explorer, String name) throws Exception {
376
        JDBCStoreParameters params = explorer.get(name);
377
        
378
        DataManager dataManager = DALLocator.getDataManager();
379
        FeatureStore store;
380
        try {
381
            store = (FeatureStore) dataManager.openStore(
382
                    getProviderName(), 
383
                    params
384
            );
385
        } catch(ValidateDataParametersException ex) {
386
            LOGGER.warn(ex.getLocalizedMessageStack());
387
            throw ex;
388
        }
389
        return store;
390
    }
391

    
392
    public void create_table_from(JDBCServerExplorer targetExplorer, String targetName, FeatureStore sourceStore) throws Exception {
393
        NewFeatureStoreParameters params = (NewFeatureStoreParameters) targetExplorer.getAddParameters(
394
                targetName
395
        );
396
        EditableFeatureType ft = params.getDefaultFeatureType();
397
        ft.addAll(sourceStore.getDefaultFeatureType());
398
        targetExplorer.add(getProviderName(), params, true);
399
    }
400
    
401
    public void insert_into_from(JDBCServerExplorer targetExplorer, String targetName, FeatureStore sourceStore, int mode) throws Exception {
402
        FeatureStore targetStore = openStore(targetExplorer, targetName);
403
        targetStore.edit(mode);
404
        try {
405
            for (Feature sourceFeature : sourceStore.getFeatureSet()) {
406
                EditableFeature targetFeature = targetStore.createNewFeature(sourceFeature);
407
                targetStore.insert(targetFeature);
408
            }
409
        } finally {
410
            targetStore.finishEditing();
411
        }
412
    }
413
    
414
    public JDBCServerExplorer openServerExplorer(String dbname) throws Exception {        
415
        DataManager dataManager = DALLocator.getDataManager();
416
        JDBCServerExplorerParameters params = this.getServerExplorerParameters(dbname);
417
        JDBCServerExplorer explorer = (JDBCServerExplorer) dataManager.openServerExplorer(
418
                this.getProviderName(), 
419
                params
420
        );
421
        return explorer;
422
    }
423

    
424
    public void drop_tables(JDBCServerExplorer explorer, String...tables) throws Exception {
425
        for (String table : tables) {
426
            String sql = "DROP TABLE IF EXISTS \""+table+"\"";
427
            explorer.execute(sql);
428
            removeResource(explorer, table, "dal");
429
        }
430
    }
431
    
432
    public void initWorkspace(String name) throws Exception {
433
        JDBCServerExplorer explorer = this.openServerExplorer(name);
434
        DataManager manager = DALLocator.getDataManager();
435
        DatabaseWorkspaceManager ws = manager.createDatabaseWorkspaceManager(explorer.getParameters());
436
        ws.connect();
437
        if (!ws.existsTable(DatabaseWorkspaceManager.TABLE_CONFIGURATION)) {
438
            ws.createTable(DatabaseWorkspaceManager.TABLE_CONFIGURATION);
439
        }
440
        if (!ws.existsTable(DatabaseWorkspaceManager.TABLE_RESOURCES)) {
441
            ws.createTable(DatabaseWorkspaceManager.TABLE_RESOURCES);
442
        }
443
    }
444
    
445
//    public abstract String getExpectedResourcesPrefix(); // Ex. "h2spatial"
446

    
447
    public abstract String getExpectedsPath();
448
    
449
    public abstract JDBCHelper createJDBCHelper() throws Exception;
450

    
451
    public abstract String getProviderName();
452
    
453
    public abstract JDBCServerExplorerParameters getServerExplorerParameters(String dbname) throws Exception;
454
}