Revision 46101

View differences:

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/AbstractTestComputedAttributes.java
1
package org.gvsig.fmap.dal.store.jdbc2;
2

  
3
import java.util.ArrayList;
4
import java.util.List;
5
import junit.framework.TestCase;
6
import static junit.framework.TestCase.assertEquals;
7
import org.gvsig.expressionevaluator.ExpressionUtils;
8
import org.gvsig.fmap.dal.DataTypes;
9
import org.gvsig.fmap.dal.feature.EditableFeatureAttributeDescriptor;
10
import org.gvsig.fmap.dal.feature.EditableFeatureType;
11
import org.gvsig.fmap.dal.feature.Feature;
12
import org.gvsig.fmap.dal.feature.FeatureQuery;
13
import org.gvsig.fmap.dal.feature.FeatureStore;
14
import org.gvsig.fmap.dal.feature.FeatureType;
15
import org.gvsig.fmap.dal.impl.expressionevaluator.DefaultFeatureAttributeEmulatorExpression;
16
import org.gvsig.tools.dispose.DisposeUtils;
17
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
18
import org.slf4j.Logger;
19
import org.slf4j.LoggerFactory;
20

  
21
public abstract class AbstractTestComputedAttributes extends TestCase {
22
    
23
    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestComputedAttributes.class);
24

  
25
    protected AbstractTestUtils utils;
26

  
27
    public AbstractTestComputedAttributes(String testName) {
28
        super(testName);
29
    }
30
    
31
    @Override
32
    protected void setUp() throws Exception {
33
        super.setUp();
34
        new DefaultLibrariesInitializer().fullInitialize();
35
    }
36
    
37
    @Override
38
    protected void tearDown() throws Exception {
39
        super.tearDown();
40
    }
41
    
42
    public AbstractTestUtils utils() {
43
        if (this.utils == null) {
44
            this.utils = this.createUtils();
45
        }
46
        return this.utils;
47
    }
48

  
49
    protected abstract AbstractTestUtils createUtils();
50
    
51
    // TODO add test methods here. The name must begin with 'test'. For example:
52
    // public void testHello() {}
53
    
54
    public void testComputed1() throws Exception {
55
        if( !utils().isTheDatabaseAvailable() ) {
56
            return;
57
        }
58
        FeatureStore sourceStore = utils().openSourceStore2();
59
        JDBCServerExplorer explorer = utils().openServerExplorer("testCreate");
60

  
61
        utils().info_jdbc(explorer);
62

  
63
        utils().drop_tables(explorer, "testCreateTarget2");
64
        utils().create_table_from(explorer, "testCreateTarget2", sourceStore);
65
        utils().insert_into_from(explorer, "testCreateTarget2", sourceStore, FeatureStore.MODE_APPEND);
66
      
67
        FeatureStore dbstore = utils().openStore(explorer,"testCreateTarget2");
68
        dbstore.edit();
69
        FeatureType featureType = dbstore.getDefaultFeatureType();
70
        EditableFeatureType eFeatureType = featureType.getEditable();
71
        eFeatureType.add("Compu1", 
72
                DataTypes.INTEGER, 
73
                new DefaultFeatureAttributeEmulatorExpression(
74
                        eFeatureType, 
75
                        ExpressionUtils.createExpression("ID*2")
76
                ));
77
        eFeatureType.add("Compu2", 
78
                DataTypes.INTEGER, 
79
                new DefaultFeatureAttributeEmulatorExpression(
80
                        eFeatureType, 
81
                        ExpressionUtils.createExpression("Poblacion+10000+Compu1")
82
                ));
83
        dbstore.update(eFeatureType);
84
        dbstore.finishEditing();
85
        List<Feature> features = dbstore.getFeatures();
86
        for (int i = 0; i < features.size(); i++) {
87
            Feature feature = features.get(i);
88
            assertEquals("Compu1 "+i, feature.getInt("ID") * 2, feature.getInt("Compu1"));
89
            if(feature.get("Poblacion")==null) {
90
                assertEquals("Compu2 "+i, null, feature.get("Compu2"));
91
            } else {
92
                assertEquals("Compu2 "+i, feature.getInt("Poblacion") + 10000 + feature.getInt("Compu1"), feature.getInt("Compu2"));
93
            }
94
        }
95
        DisposeUtils.dispose(dbstore);
96
    }
97
    
98
    @SuppressWarnings("UnusedAssignment")
99
    public void testComputed2() throws Exception {
100
        if( !utils().isTheDatabaseAvailable() ) {
101
            return;
102
        }
103
        String testTableName = "testComputedAttributes2";
104
        JDBCServerExplorer explorer = utils().openServerExplorer("computedAttr");
105

  
106
        utils().info_jdbc(explorer);
107
        utils().drop_tables(explorer, testTableName);
108
        
109
        FeatureStore sourceStore = utils().openSourceStore2();
110
        
111
        utils().create_table_from(explorer, testTableName, sourceStore);
112
        utils().insert_into_from(explorer, testTableName, sourceStore, FeatureStore.MODE_APPEND);
113
      
114
        FeatureStore dbstore = utils().openStore(explorer,testTableName);
115
        
116
        dbstore.edit();
117
        FeatureType featureType = dbstore.getDefaultFeatureType();
118
        EditableFeatureType eFeatureType = featureType.getEditable();
119
        FeatureQuery query = sourceStore.createFeatureQuery();
120
        eFeatureType.add("CompuID", 
121
                DataTypes.INTEGER, 
122
                new DefaultFeatureAttributeEmulatorExpression(
123
                        eFeatureType, 
124
                        ExpressionUtils.createExpression("MOD(ID,10)")
125
                ));
126
        eFeatureType.add("CompuPob", 
127
                DataTypes.INTEGER, 
128
                new DefaultFeatureAttributeEmulatorExpression(
129
                        eFeatureType, 
130
                        ExpressionUtils.createExpression("Poblacion+1")
131
                ));
132
        eFeatureType.add("CompuProv", 
133
                DataTypes.STRING, 
134
                new DefaultFeatureAttributeEmulatorExpression(
135
                        eFeatureType, 
136
                        ExpressionUtils.createExpression("UPPER(Provincia)")
137
                ));
138
        EditableFeatureAttributeDescriptor extraColumn1 = 
139
                query.getExtraColumn().add("ExtraID900", DataTypes.INTEGER);
140
        EditableFeatureAttributeDescriptor extraColumn2 = 
141
                query.getExtraColumn().add("ExtraPobDen", DataTypes.INTEGER);
142
        EditableFeatureAttributeDescriptor extraColumn3 = 
143
                query.getExtraColumn().add("ExtraAno", DataTypes.INTEGER);
144

  
145
        extraColumn1.setFeatureAttributeEmulator(
146
                new DefaultFeatureAttributeEmulatorExpression(
147
                        eFeatureType, 
148
                        ExpressionUtils.createExpression("CompuID+900")));
149
        extraColumn2.setFeatureAttributeEmulator(
150
                new DefaultFeatureAttributeEmulatorExpression(
151
                        eFeatureType, 
152
                        ExpressionUtils.createExpression("CompuPob+Densidad")));
153
        extraColumn3.setFeatureAttributeEmulator(
154
                new DefaultFeatureAttributeEmulatorExpression(
155
                        eFeatureType, 
156
                        ExpressionUtils.createExpression("EXTRACT(YEAR FROM Fecha)")));
157
	
158
        query.getGroupByColumns().add("Comunidad");
159
        query.getGroupByColumns().add("CompuProv");
160
        query.getGroupByColumns().add("ExtraAno");
161
        query.getAggregateFunctions().put("ID", "MIN");
162
        query.getAggregateFunctions().put("Poblacion", "MIN");
163
        query.getAggregateFunctions().put("CompuID", "MIN");
164
        query.getAggregateFunctions().put("CompuPob", "SUM");
165
        query.getAggregateFunctions().put("ExtraID900", "SUM");
166
        query.getAggregateFunctions().put("ExtraPobDen", "SUM");
167
        dbstore.update(eFeatureType);
168
        dbstore.finishEditing();
169
        
170
        
171
        List<Feature> features0 = dbstore.getFeatures(query);
172
        ArrayList<Feature> features = new ArrayList<>();
173
        
174
        System.out.println("ID,Comunidad,Provincia,Ciudad,Poblacion,Densidad,Fecha,CompuID,CompuPob,CompuProv,ExtraID900,ExtraPobDen,ExtraAno");
175
        for (int i = 0; i < features0.size(); i++) {
176
            Feature feature = features0.get(i);
177
            features.add(feature.getCopy());
178
	    System.out.print(feature.toString());
179
	    System.out.print(","+feature.get("ExtraID900"));
180
	    System.out.print(","+feature.get("ExtraPobDen"));
181
	    System.out.println(","+feature.get("ExtraAno"));
182
        }
183
        System.out.println("ID,Comunidad,Provincia,Ciudad,Poblacion,Densidad,Fecha,CompuID,CompuPob,CompuProv,ExtraID900,ExtraPobDen,ExtraAno");
184
	
185
        features0 = null;
186
	String[] header = new String[]{"ID","Comunidad","Provincia","Ciudad","Poblacion","Densidad","Fecha","CompuID","CompuPob","CompuProv","ExtraID900","ExtraPobDen","ExtraAno"};
187
	ArrayList<Object[]> values = new ArrayList<>();
188
	values.add(new Object[]{0, null, null, null, null, null, null, 0, null,"",900,null,null});
189
	values.add(new Object[]{1, "GVA", null, null, 500, null, null, 1, 1502, "VALENCIA",1803,1505,2019});
190
	values.add(new Object[]{3, "GVA", null, null, 50, null, null, 3, 352, "VALENCIA",1807,359,2020});
191
	values.add(new Object[]{5, "GVA", null, null, 200, null, null, 5, 201, "ALICANTE",905,206,2019});
192
	values.add(new Object[]{6, "GVA", null, null, 20, null, null, 6, 422, "ALICANTE",1813,1135,2020});
193
	values.add(new Object[]{8, "GVA", null, null, 100, null, null, 8, 702, "CASTELLON",1817,719,2019});
194
	for (int i = 0; i < features.size(); i++) {
195
		for (int j = 0; j < header.length; j++) {
196
			assertEquals("feature["+i+"]["+header[j]+"]:", values.get(i)[j],features.get(i).get(header[j]));
197
		}
198
	}
199

  
200
        DisposeUtils.dispose(dbstore);
201
    }
202

  
203
}
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/AbstractTestExport2db.java
1
package org.gvsig.fmap.dal.store.jdbc2;
2

  
3
import junit.framework.TestCase;
4
import static junit.framework.TestCase.assertEquals;
5
import org.gvsig.fmap.dal.DatabaseWorkspaceManager;
6
import org.gvsig.fmap.dal.feature.EditableFeatureType;
7
import org.gvsig.fmap.dal.feature.FeatureStore;
8
import org.gvsig.fmap.dal.feature.FeatureType;
9
import org.gvsig.tools.dispose.DisposeUtils;
10
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
11
import org.slf4j.Logger;
12
import org.slf4j.LoggerFactory;
13

  
14
public abstract class AbstractTestExport2db extends TestCase {
15

  
16
    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestExport2db.class);
17

  
18
    protected AbstractTestUtils utils;
19

  
20
    public AbstractTestExport2db(String testName) {
21
        super(testName);
22
    }
23

  
24
    @Override
25
    protected void setUp() throws Exception {
26
        super.setUp();
27
        new DefaultLibrariesInitializer().fullInitialize();
28
    }
29

  
30
    @Override
31
    protected void tearDown() throws Exception {
32
        super.tearDown();
33
    }
34

  
35
    public AbstractTestUtils utils() {
36
        if (this.utils == null) {
37
            this.utils = this.createUtils();
38
        }
39
        return this.utils;
40
    }
41

  
42
    protected abstract AbstractTestUtils createUtils();
43

  
44
    // TODO add test methods here. The name must begin with 'test'. For example:
45
    // public void testHello() {}
46
    public void testExport1() throws Exception {
47
        try {
48
            if (!utils().isTheDatabaseAvailable()) {
49
                return;
50
            }
51
            FeatureStore sourceStore = utils().openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/continentes_nogeom.csv");
52
            JDBCServerExplorer explorer = utils().openServerExplorer("testExport1");
53

  
54
            utils().info_jdbc(explorer);
55

  
56
            // Importamos el CSV en la bbdd
57
            utils().drop_tables(explorer, "continentes", DatabaseWorkspaceManager.TABLE_RESOURCES_NAME);
58
            utils().create_table_from(explorer, "continentes", sourceStore);
59
            utils().insert_into_from(explorer, "continentes", sourceStore, FeatureStore.MODE_APPEND);
60

  
61
            // Le ponemos como Pk el campo ID
62
            FeatureStore dbstore = utils().openStore(explorer, "continentes");
63
            dbstore.edit();
64
            FeatureType featureType = dbstore.getDefaultFeatureType();
65
            EditableFeatureType eFeatureType = featureType.getEditable();
66
            eFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(true);
67
            dbstore.update(eFeatureType);
68
            dbstore.finishEditing();
69
            DisposeUtils.dispose(dbstore);
70

  
71
            // Comprobamos los campos que tiene la tabla de la bbdd.
72
            utils().removeResource(explorer, "continentes", "dal");
73

  
74
            dbstore = utils().openStore(explorer, "continentes");
75
            featureType = dbstore.getDefaultFeatureType();
76
            assertEquals("Fields count", 2, featureType.size());
77

  
78
            assertEquals("Field(0).name", "ID", featureType.getAttributeDescriptor(0).getName());
79
            assertEquals("Field(1).name", "NAME", featureType.getAttributeDescriptor(1).getName());
80

  
81
            assertEquals("Field(ID).isPrimaryKey", true, featureType.getAttributeDescriptor(0).isPrimaryKey());
82
            assertEquals("Field(NAME).isPrimaryKey", false, featureType.getAttributeDescriptor(1).isPrimaryKey());
83
            assertEquals("Field(ID).isIndexed", true, featureType.getAttributeDescriptor(0).isIndexed());
84
            assertEquals("Field(NAME).isIndexed", false, featureType.getAttributeDescriptor(1).isIndexed());
85

  
86
            // Le ponemos como Pk el campo NAME y lo quitamos del ID
87
            dbstore = utils().openStore(explorer, "continentes");
88
            dbstore.edit();
89
            featureType = dbstore.getDefaultFeatureType();
90
            eFeatureType = featureType.getEditable();
91
            eFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(false);
92
            eFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(true);
93
            dbstore.update(eFeatureType);
94
            dbstore.finishEditing();
95
            DisposeUtils.dispose(dbstore);
96

  
97
            // Comprobamos los campos que tiene la tabla de la bbdd.
98
            utils().removeResource(explorer, "continentes", "dal");
99

  
100
            dbstore = utils().openStore(explorer, "continentes");
101
            featureType = dbstore.getDefaultFeatureType();
102
            assertEquals("Fields count", 2, featureType.size());
103

  
104
            assertEquals("Field(0).name", "ID", featureType.getAttributeDescriptor(0).getName());
105
            assertEquals("Field(1).name", "NAME", featureType.getAttributeDescriptor(1).getName());
106

  
107
            assertEquals("Field(ID).isPrimaryKey", false, featureType.getAttributeDescriptor(0).isPrimaryKey());
108
            assertEquals("Field(NAME).isPrimaryKey", true, featureType.getAttributeDescriptor(1).isPrimaryKey());
109
            assertEquals("Field(ID).isIndexed", false, featureType.getAttributeDescriptor(0).isIndexed());
110
            assertEquals("Field(NAME).isIndexed", true, featureType.getAttributeDescriptor(1).isIndexed());
111

  
112
            DisposeUtils.dispose(dbstore);
113

  
114
            // Le ponemos como Pk el campo NAME y lo quitamos del ID
115
            dbstore = utils().openStore(explorer, "continentes");
116
            dbstore.edit();
117
            featureType = dbstore.getDefaultFeatureType();
118
            eFeatureType = featureType.getEditable();
119
            eFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(false);
120
            eFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(true);
121

  
122
            eFeatureType.getEditableAttributeDescriptor("ID").setIsIndexed(true);
123
            eFeatureType.getEditableAttributeDescriptor("NAME").setIsIndexed(true);
124
            dbstore.update(eFeatureType);
125
            dbstore.finishEditing();
126
            DisposeUtils.dispose(dbstore);
127

  
128
            // Comprobamos los campos que tiene la tabla de la bbdd.
129
            utils().removeResource(explorer, "continentes", "dal");
130

  
131
            dbstore = utils().openStore(explorer, "continentes");
132
            featureType = dbstore.getDefaultFeatureType();
133
            assertEquals("Fields count", 2, featureType.size());
134

  
135
            assertEquals("Field(0).name", "ID", featureType.getAttributeDescriptor(0).getName());
136
            assertEquals("Field(1).name", "NAME", featureType.getAttributeDescriptor(1).getName());
137

  
138
            assertEquals("Field(ID).isPrimaryKey", false, featureType.getAttributeDescriptor(0).isPrimaryKey());
139
            assertEquals("Field(NAME).isPrimaryKey", true, featureType.getAttributeDescriptor(1).isPrimaryKey());
140
            assertEquals("Field(ID).isIndexed", true, featureType.getAttributeDescriptor(0).isIndexed());
141
            assertEquals("Field(NAME).isIndexed", true, featureType.getAttributeDescriptor(1).isIndexed());
142

  
143

  
144
            DisposeUtils.dispose(dbstore);
145
        } catch (Throwable th) {
146
            LOGGER.warn("", th);
147
            throw th;
148
        }
149
    }
150

  
151
}
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/operations/sql/AbstractTestPerformChangesUpdateStructure.java
1
package org.gvsig.fmap.dal.store.jdbc2.operations.sql;
2

  
3
import java.util.Collections;
4
import java.util.List;
5
import junit.framework.TestCase;
6
import org.gvsig.fmap.dal.feature.EditableFeatureType;
7
import org.gvsig.fmap.dal.feature.FeatureStore;
8
import org.gvsig.fmap.dal.feature.FeatureType;
9
import org.gvsig.fmap.dal.store.jdbc2.AbstractTestUtils;
10
import org.gvsig.fmap.dal.store.jdbc2.AbstractTestUtils.Expecteds;
11
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
12
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
13
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
14
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
15
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.PerformChangesOperation;
16
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
17
import org.slf4j.Logger;
18
import org.slf4j.LoggerFactory;
19

  
20
@SuppressWarnings("UseSpecificCatch")
21
public abstract class AbstractTestPerformChangesUpdateStructure extends TestCase {
22

  
23
    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestPerformChangesUpdateStructure.class);
24

  
25
    protected AbstractTestUtils utils;
26

  
27
    public AbstractTestPerformChangesUpdateStructure(String testName) {
28
        super(testName);
29
    }
30

  
31
    @Override
32
    protected void setUp() throws Exception {
33
        super.setUp();
34
        new DefaultLibrariesInitializer().fullInitialize();
35
    }
36

  
37
    @Override
38
    protected void tearDown() throws Exception {
39
        super.tearDown();
40
    }
41

  
42
    public AbstractTestUtils utils() {
43
        if (this.utils == null) {
44
            this.utils = this.createUtils();
45
        }
46
        return this.utils;
47
    }
48

  
49
    protected abstract AbstractTestUtils createUtils();
50

  
51
    public void testPerformChangesAddPk() throws Exception {
52
        JDBCHelper helper = utils().createJDBCHelper();
53
        JDBCSQLBuilderBase sqlbuilder = helper.createSQLBuilder();
54
        OperationsFactory operations = helper.getOperations();
55

  
56
        Expecteds expecteds = utils().getExpecteds("performChangesUpdateStructure.txt");
57

  
58
        FeatureStore sourceStore = utils().openSourceStore1();
59

  
60
        TableReference table = operations.createTableReference(
61
                "dbtest",
62
                sqlbuilder.default_schema(),
63
                "test",
64
                null
65
        );
66
        FeatureType featureType = sourceStore.getDefaultFeatureType();
67

  
68
        FeatureType.FeatureTypeChanged featureTypeChanged = new FeatureType.FeatureTypeChanged() {
69
            @Override
70
            public FeatureType getSource() {
71
                EditableFeatureType ft = featureType.getCopy().getEditable();
72
                ft.getEditableAttributeDescriptor("ID").setIsPrimaryKey(false);
73
                return ft;
74
            }
75

  
76
            @Override
77
            public FeatureType getTarget() {
78
                return featureType;
79
            }
80
        };
81
        List<FeatureType.FeatureTypeChanged> featureTypesChangeds = Collections.singletonList(featureTypeChanged);
82

  
83
        PerformChangesOperation performChanges = operations.createPerformChanges(
84
                table,
85
                sourceStore.getDefaultFeatureType(),
86
                null,
87
                null,
88
                null,
89
                featureTypesChangeds.iterator()
90
        );
91
        List<String> updateTableSQLs = performChanges.getUpdateTableSQLs();
92
        
93
        for (int i = 0; i < expecteds.size("PerformChangesAddPk"); i++) {
94
            System.out.println("###### EXP[" + i + "]:" + expecteds.get("PerformChangesAddPk",i) + "###");
95
        }
96
        for (int i = 0; i < updateTableSQLs.size(); i++) {
97
            System.out.println("###### SQL[" + i + "]:" + updateTableSQLs.get(i) + "###");
98
        }
99

  
100
        assertEquals("num sqls", expecteds.size("PerformChangesAddPk"), updateTableSQLs.size());
101
        for (int i = 0; i < updateTableSQLs.size(); i++) {
102
            assertEquals("Check "+i, expecteds.get("PerformChangesAddPk",i), updateTableSQLs.get(i));
103
        }
104
    }
105

  
106
    public void testChangePk1() throws Exception {
107
        JDBCHelper helper = utils().createJDBCHelper();
108
        JDBCSQLBuilderBase sqlbuilder = helper.createSQLBuilder();
109
        OperationsFactory operations = helper.getOperations();
110

  
111
        Expecteds expecteds = utils().getExpecteds("performChangesUpdateStructure.txt");
112

  
113
        FeatureStore sourceStore = utils().openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/continentes_nogeom.csv");
114

  
115
        TableReference table = operations.createTableReference(
116
                "dbtest",
117
                sqlbuilder.default_schema(),
118
                "test",
119
                null
120
        );
121
        EditableFeatureType sourceFeatureType = sourceStore.getDefaultFeatureType().getCopy().getEditable();
122
        EditableFeatureType targetFeatureType = sourceStore.getDefaultFeatureType().getCopy().getEditable();
123
        
124
        sourceFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(false);
125
        sourceFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(false);
126

  
127
        targetFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(true);
128
        targetFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(false);
129

  
130
        FeatureType.FeatureTypeChanged featureTypeChanged = new FeatureType.FeatureTypeChanged() {
131
            @Override
132
            public FeatureType getSource() {
133
                return sourceFeatureType;
134
            }
135

  
136
            @Override
137
            public FeatureType getTarget() {
138
                return targetFeatureType;
139
            }
140
        };
141
        List<FeatureType.FeatureTypeChanged> featureTypesChangeds = Collections.singletonList(featureTypeChanged);
142

  
143
        PerformChangesOperation performChanges = operations.createPerformChanges(
144
                table,
145
                sourceStore.getDefaultFeatureType(),
146
                null,
147
                null,
148
                null,
149
                featureTypesChangeds.iterator()
150
        );
151
        List<String> updateTableSQLs = performChanges.getUpdateTableSQLs();
152
        
153
        for (int i = 0; i < expecteds.size("changePk1"); i++) {
154
            System.out.println("###### EXP[" + i + "]:" + expecteds.get("changePk1",i) + "###");
155
        }
156
        for (int i = 0; i < updateTableSQLs.size(); i++) {
157
            System.out.println("###### SQL[" + i + "]:" + updateTableSQLs.get(i) + "###");
158
        }
159

  
160
        assertEquals("num sqls", expecteds.size("changePk1"), updateTableSQLs.size());
161
        for (int i = 0; i < updateTableSQLs.size(); i++) {
162
            assertEquals("Check "+i, expecteds.get("changePk1",i), updateTableSQLs.get(i));
163
        }
164
    }
165

  
166
    public void testChangePk2() throws Exception {
167
        JDBCHelper helper = utils().createJDBCHelper();
168
        JDBCSQLBuilderBase sqlbuilder = helper.createSQLBuilder();
169
        OperationsFactory operations = helper.getOperations();
170

  
171
        Expecteds expecteds = utils().getExpecteds("performChangesUpdateStructure.txt");
172

  
173
        FeatureStore sourceStore = utils().openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/continentes_nogeom.csv");
174

  
175
        TableReference table = operations.createTableReference(
176
                "dbtest",
177
                sqlbuilder.default_schema(),
178
                "test",
179
                null
180
        );
181
        EditableFeatureType sourceFeatureType = sourceStore.getDefaultFeatureType().getCopy().getEditable();
182
        EditableFeatureType targetFeatureType = sourceStore.getDefaultFeatureType().getCopy().getEditable();
183
        
184
        sourceFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(true);
185
        sourceFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(false);
186

  
187
        targetFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(false);
188
        targetFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(true);
189

  
190
        FeatureType.FeatureTypeChanged featureTypeChanged = new FeatureType.FeatureTypeChanged() {
191
            @Override
192
            public FeatureType getSource() {
193
                return sourceFeatureType;
194
            }
195

  
196
            @Override
197
            public FeatureType getTarget() {
198
                return targetFeatureType;
199
            }
200
        };
201
        List<FeatureType.FeatureTypeChanged> featureTypesChangeds = Collections.singletonList(featureTypeChanged);
202

  
203
        PerformChangesOperation performChanges = operations.createPerformChanges(
204
                table,
205
                sourceStore.getDefaultFeatureType(),
206
                null,
207
                null,
208
                null,
209
                featureTypesChangeds.iterator()
210
        );
211
        List<String> updateTableSQLs = performChanges.getUpdateTableSQLs();
212
        
213
        for (int i = 0; i < expecteds.size("changePk2"); i++) {
214
            System.out.println("###### EXP[" + i + "]:" + expecteds.get("changePk2",i) + "###");
215
        }
216
        for (int i = 0; i < updateTableSQLs.size(); i++) {
217
            System.out.println("###### SQL[" + i + "]:" + updateTableSQLs.get(i) + "###");
218
        }
219

  
220
        assertEquals("num sqls", expecteds.size("changePk2"), updateTableSQLs.size());
221
        for (int i = 0; i < updateTableSQLs.size(); i++) {
222
            assertEquals("Check "+i, expecteds.get("changePk2",i), updateTableSQLs.get(i));
223
        }
224
    }
225

  
226
    public void testChangePk3() throws Exception {
227
        JDBCHelper helper = utils().createJDBCHelper();
228
        JDBCSQLBuilderBase sqlbuilder = helper.createSQLBuilder();
229
        OperationsFactory operations = helper.getOperations();
230

  
231
        Expecteds expecteds = utils().getExpecteds("performChangesUpdateStructure.txt");
232

  
233
        FeatureStore sourceStore = utils().openCSVStore("/org/gvsig/fmap/dal/store/jdbc2/continentes_nogeom.csv");
234

  
235
        TableReference table = operations.createTableReference(
236
                "dbtest",
237
                sqlbuilder.default_schema(),
238
                "test",
239
                null
240
        );
241
        EditableFeatureType sourceFeatureType = sourceStore.getDefaultFeatureType().getCopy().getEditable();
242
        EditableFeatureType targetFeatureType = sourceStore.getDefaultFeatureType().getCopy().getEditable();
243
        
244
        sourceFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(true);
245
        sourceFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(false);
246

  
247
        targetFeatureType.getEditableAttributeDescriptor("ID").setIsPrimaryKey(false);
248
        targetFeatureType.getEditableAttributeDescriptor("NAME").setIsPrimaryKey(false);
249
        
250
        targetFeatureType.getEditableAttributeDescriptor("ID").setIsIndexed(true);
251
        targetFeatureType.getEditableAttributeDescriptor("NAME").setIsIndexed(true);
252

  
253
        FeatureType.FeatureTypeChanged featureTypeChanged = new FeatureType.FeatureTypeChanged() {
254
            @Override
255
            public FeatureType getSource() {
256
                return sourceFeatureType;
257
            }
258

  
259
            @Override
260
            public FeatureType getTarget() {
261
                return targetFeatureType;
262
            }
263
        };
264
        List<FeatureType.FeatureTypeChanged> featureTypesChangeds = Collections.singletonList(featureTypeChanged);
265

  
266
        PerformChangesOperation performChanges = operations.createPerformChanges(
267
                table,
268
                sourceStore.getDefaultFeatureType(),
269
                null,
270
                null,
271
                null,
272
                featureTypesChangeds.iterator()
273
        );
274
        List<String> updateTableSQLs = performChanges.getUpdateTableSQLs();
275
        
276
        System.out.println("###### testChangePk3");
277
        for (int i = 0; i < expecteds.size("changePk3"); i++) {
278
            System.out.println("###### EXP[" + i + "]:" + expecteds.get("changePk3",i) + "###");
279
        }
280
        for (int i = 0; i < updateTableSQLs.size(); i++) {
281
            System.out.println("###### SQL[" + i + "]:" + updateTableSQLs.get(i) + "###");
282
        }
283

  
284
        assertEquals("num sqls", expecteds.size("changePk3"), updateTableSQLs.size());
285
        for (int i = 0; i < updateTableSQLs.size(); i++) {
286
            assertEquals("Check "+i, expecteds.get("changePk3",i), updateTableSQLs.get(i));
287
        }
288
    }
289
    
290
}
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/operations/sql/AbstractTestCount.java
1
package org.gvsig.fmap.dal.store.jdbc2.operations.sql;
2

  
3
import junit.framework.TestCase;
4
import static junit.framework.TestCase.assertEquals;
5
import org.gvsig.fmap.dal.feature.FeatureQuery;
6
import org.gvsig.fmap.dal.feature.FeatureStore;
7
import org.gvsig.fmap.dal.feature.FeatureType;
8
import org.gvsig.fmap.dal.store.jdbc2.AbstractTestUtils;
9
import org.gvsig.fmap.dal.store.jdbc2.AbstractTestUtils.Expecteds;
10
import org.gvsig.fmap.dal.store.jdbc2.JDBCHelper;
11
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory;
12
import org.gvsig.fmap.dal.store.jdbc2.OperationsFactory.TableReference;
13
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
14
import org.gvsig.fmap.dal.store.jdbc2.spi.operations.CountOperation;
15
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
16
import org.slf4j.Logger;
17
import org.slf4j.LoggerFactory;
18

  
19
@SuppressWarnings("UseSpecificCatch")
20
public abstract class AbstractTestCount extends TestCase {
21

  
22
    protected static final Logger LOGGER = LoggerFactory.getLogger(AbstractTestCount.class);
23

  
24
    protected AbstractTestUtils utils;
25

  
26
    public AbstractTestCount(String testName) {
27
        super(testName);
28
    }
29

  
30
    @Override
31
    protected void setUp() throws Exception {
32
        super.setUp();
33
        new DefaultLibrariesInitializer().fullInitialize();
34
    }
35

  
36
    @Override
37
    protected void tearDown() throws Exception {
38
        super.tearDown();
39
    }
40

  
41
    public AbstractTestUtils utils() {
42
        if (this.utils == null) {
43
            this.utils = this.createUtils();
44
        }
45
        return this.utils;
46
    }
47

  
48
    protected abstract AbstractTestUtils createUtils();
49

  
50
    public void testCount() throws Exception {
51
        try {
52
            JDBCHelper helper = utils().createJDBCHelper();
53
            JDBCSQLBuilderBase sqlbuilder = helper.createSQLBuilder();
54
            OperationsFactory operations = helper.getOperations();
55

  
56
            Expecteds expectedSQLs = utils().getExpecteds("count.txt");
57

  
58
            FeatureStore sourceStore = utils().openSourceStore1();
59

  
60
            TableReference table = operations.createTableReference(
61
                    "dbtest",
62
                    sqlbuilder.default_schema(),
63
                    "test",
64
                    null
65
            );
66
            FeatureType featureType = sourceStore.getDefaultFeatureType();
67
            CountOperation count = operations.createCount(
68
                    featureType,
69
                    table,
70
                    null,
71
                    null
72
            );
73

  
74
            String sql = count.getSQL();
75
            System.out.println("###### SQL:" + sql+"###");
76
            System.out.println("###### EXP:" + expectedSQLs.get("count")+"###");
77

  
78
            assertEquals("Count SQL", expectedSQLs.get("count"), sql);
79
        } catch (Throwable th) {
80
            LOGGER.warn("", th);
81
            throw th;
82
        }
83
    }
84

  
85
    public void testSimpleGroup() throws Exception {
86
        try {
87
            JDBCHelper helper = utils().createJDBCHelper();
88
            JDBCSQLBuilderBase sqlbuilder = helper.createSQLBuilder();
89
            OperationsFactory operations = helper.getOperations();
90

  
91
            Expecteds expectedSQLs = utils().getExpecteds("count.txt");
92

  
93
            FeatureStore sourceStore = utils().openSourceStore1();
94

  
95
            TableReference table = operations.createTableReference(
96
                    "dbtest",
97
                    sqlbuilder.default_schema(),
98
                    "test",
99
                    null
100
            );
101
            FeatureType featureType = sourceStore.getDefaultFeatureType();
102
            FeatureQuery query = sourceStore.createFeatureQuery();
103
            query.getGroupByColumns().add("Long");
104
            query.getAggregateFunctions().put("ID", "MIN");
105
            query.getAggregateFunctions().put("Byte", "MAX");
106
            query.getAggregateFunctions().put("Double", "SUM");
107
            query.getOrder().add("Long");
108
            CountOperation count = operations.createCount(
109
                    featureType,
110
                    table,
111
                    null,
112
                    query
113
            );
114
            String sql = count.getSQL();
115
            System.out.println("###### SQL:" + sql+"###");
116
            System.out.println("###### EXP:" + expectedSQLs.get("SimpleGroup")+"###");
117

  
118
            assertEquals("Count with group SQL", expectedSQLs.get("SimpleGroup"), sql);
119
        } catch (Throwable th) {
120
            LOGGER.warn("", th);
121
            throw th;
122
        }
123
    }
124

  
125
    // TODO: a?adir un test con where, group y order.
126
}
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
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.DatabaseWorkspaceManager;
23
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.FIELD_RESOURCES_NAME;
24
import static org.gvsig.fmap.dal.DatabaseWorkspaceManager.TABLE_RESOURCES_NAME;
25
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
26
import org.gvsig.fmap.dal.feature.EditableFeature;
27
import org.gvsig.fmap.dal.feature.EditableFeatureType;
28
import org.gvsig.fmap.dal.feature.Feature;
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.store.jdbc.JDBCServerExplorerParameters;
34
import org.gvsig.fmap.dal.store.jdbc.JDBCStoreParameters;
35
import org.gvsig.tools.resourcesstorage.ResourcesStorage;
36
import org.gvsig.tools.util.HasAFile;
37
import org.hibernate.dialect.H2Dialect;
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 = AbstractTestUtils.class.getResource("/");
55
        File x = new File(url.toURI());
56
        File target = x.getParentFile();
57
        return target;
58
    }
59

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

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

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

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

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

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

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

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

  
131
    public static class Expecteds {
132

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

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

  
139
        private static class CommandLine {
140

  
141
            private final String[] cmd;
142

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  
423
    public void drop_tables(JDBCServerExplorer explorer, String...tables) {
424
        for (String table : tables) {
425
            String sql = "DROP TABLE IF EXISTS \""+table+"\"";
426
            explorer.execute(sql);
427
        }
428
    }
429
    
430
//    public abstract String getExpectedResourcesPrefix(); // Ex. "h2spatial"
431

  
432
    public abstract String getExpectedsPath();
433
    
434
    public abstract JDBCHelper createJDBCHelper() throws Exception;
435

  
436
    public abstract String getProviderName();
437
    
438
    public abstract JDBCServerExplorerParameters getServerExplorerParameters(String dbname) throws Exception;
439
}
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/resources/org/gvsig/fmap/dal/store/jdbc2/testCreateSource1.csv
1
ID/Integer/set/pk=true;Byte/Byte;Bool1/Boolean;Long/Long;Timestamp/TimeStamp;Date/Date;Time/Time;Bool2/Boolean;String/String/set/size=30;Bool3/Boolean;Double/Double;Bool4/Boolean;Float/Float;Bool5/Boolean;Decimal/Decimal/set/precision=6/set/scale=3;Geometry/Geometry/set/geomtype=Point:2D/set/srs=EPSG:4326
2
0;  ; ;    ;              ;        ;      ; ;      ; ;           ; ;      ;T;       ;
3
1;10;T;1000;20191229121314;20191229;121314;T;Yo yo1;F;12345.54321;T;123.21;T;456.123;POINT (-3.8945156972987958 42.01053743584765)
4
2;20;T;2000;20191129121314;20191129;131314;T;Yo yo2;F;12100.54321;T;100.21;T;456.123;POINT (-2.1079618220646115 41.983079082675474)
5
3;30;T;3000;20191029121314;20191029;141314;T;Yo yo3;F;12101.54321;T;101.21;T;456.123;POINT (-2.57249737803327 41.35372113353277)
6
4;40;T;4000;20190929121314;20190929;151314;T;Yo yo4;F;12102.54321;T;102.21;T;456.123;POINT (-4.061822048036304 41.35877680235475)
7
5;50;T;5000;20190829121314;20190829;161314;T;Yo yo5;F;12103.54321;T;103.21;T;456.123;POINT (-3.974317066986988 40.78701209315094)
8
6;60;T;6000;20190729121314;20190729;171314;T;Yo yo6;F;12104.54321;T;104.21;T;456.123;POINT (-2.510509736717547 40.69847453392384)
9
7;70;T;7000;20190629121314;20190629;181314;T;Yo yo7;F;12105.54321;T;105.21;T;456.123;POINT (-0.5317736981843011 40.66396082637622)
10
8;80;T;8000;20190529121314;20190529;191314;T;Yo yo8;F;12106.54321;T;106.21;T;456.123;POINT (-0.3626917259170671 41.13652386601604)
11
9;90;T;9000;20190429121314;20190429;201314;T;Yo yo9;F;12107.54321;T;107.21;T;456.123;POINT (-1.2461823078608523 41.84950010180092)
12
10;;T;1001;20191229121314;20191229;121314;T;Yo yo1;F;12345.54321;T;123.21;T;456.123;POINT (-1.2145405488596532 41.22158511004416)
13
11;22; ;2002;20191129121314;20191129;131314;T;Yo yo2;F;12100.54321;T;100.21;T;456.123;POINT (-0.7699089544899235 41.630581204431756)
14
12;33;T; ;20190929121314;20191029;141314;T;Yo yo3;F;12101.54321;T;101.21;T;456.123;POINT (0.4821915816701051 41.75970939133133)
15
13;41;T;4001; ;20190929;151314;T;Yo yo4;F;12102.54321;T;102.21;T;456.123;POINT (0.7912661147227479 41.919324620992036)
16
14;52;T;5002;20190829121314; ;161314;T;Yo yo5;F;12103.54321;T;103.21;T;456.123;POINT (1.052534629531243 41.493736996249545)
17
15;63;T;6003;20190729121314;20190729; ;T;Yo yo6;F;12104.54321;T;104.21;T;456.123;POINT (0.8097002367335026 41.0899480235613)
18
16;74;T;7004;20190629121314;20190629;181314;T; ;F;12105.54321;T;105.21;T;456.123;POINT (-0.4883960310112362 41.17597288081971)
19
17;85;T;8005;20190529121314;20190529;191314;T;Yo yo8;F; ;T;106.21;T;456.123;POINT (-0.6439030698437881 40.89530766155764)
20
18;96;T;9006;20190429121314;20190429;201314;T;Yo yo9;F;12107.54321;T; ;T; ;POINT (-1.3061826868199504 40.72372835570524)
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/resources/org/gvsig/fmap/dal/store/jdbc2/testCreateSource2.csv
1
ID/Integer/set/pk=true;Comunidad/String/set/size=10;Provincia/String/set/size=10;Ciudad/String/set/size=10;Poblacion/Integer;Densidad/Double;Fecha/TimeStamp
2
0;;;;;;
3
1;GVA;Valencia;Cullera;1000;1.01;20191229121314
4
2;GVA;Valencia;Pinedo;500;2.02;20191229121314
5
3;GVA;Valencia;Gandia;300;3.03;20201229121314
6
4;GVA;Valencia;Sueca;50;4.04;20201229121314
7
5;GVA;Alicante;Calpe;200;5.05;20191229121314
8
6;GVA;Alicante;Cullera;400;6.06;20201229121314
9
7;GVA;Alicante;Oliva;20;7,07;20201229121314
10
8;GVA;Castellon;Nules;100;8.08;20191229121314
11
9;GVA;Castellon;Oropesa;600;9.09;20191229121314
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/resources/org/gvsig/fmap/dal/store/jdbc2/continentes_nogeom.csv
1
"ID/Integer/set/order=0";"NAME/String/set/size=50/set/order=10"
2
"1";"Africa"
3
"2";"Antarctica"
4
"3";"Asia"
5
"4";"Australia"
6
"5";"Europe"
7
"7";"Oceania"
8
"8";"South America"
9
"9";"North America"
trunk/org.gvsig.desktop/org.gvsig.desktop.compat.cdc/org.gvsig.fmap.dal/org.gvsig.fmap.dal.db/org.gvsig.fmap.dal.db.jdbc/pom.xml
119 119
        </executions>
120 120
      </plugin>
121 121

  
122
        <plugin>
123
            <groupId>org.apache.maven.plugins</groupId>
124
            <artifactId>maven-jar-plugin</artifactId>
125
            <configuration>
126
            </configuration>
127
            <executions>
128
                <!-- Generates a jar file only with the test classes -->
129
                <execution>
130
                    <goals>
131
                        <goal>test-jar</goal>
132
                    </goals>
133
                </execution>
134
            </executions>
135
        </plugin>
122 136
    </plugins>
123 137
  </build>
124 138

  

Also available in: Unified diff