/
GamaSqlConnection.java
297 lines (255 loc) · 10.5 KB
/
GamaSqlConnection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package msi.gama.database.geosql;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.mysql.MySQLDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.filter.text.ecql.ECQL;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.jdbc.JDBCDataStoreFactory;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.Feature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import msi.gama.common.geometry.Envelope3D;
import msi.gama.common.util.FileUtils;
import msi.gama.metamodel.shape.GamaGisGeometry;
import msi.gama.metamodel.shape.IShape;
import msi.gama.metamodel.topology.projection.ProjectionFactory;
import msi.gama.runtime.GAMA;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gama.util.GamaListFactory;
import msi.gama.util.IList;
import msi.gama.util.file.GamaGisFile;
import msi.gaml.types.IType;
import msi.gaml.types.Types;
import ummisco.gama.dev.utils.DEBUG;
// DataStore.dispose(); //close connection;
@SuppressWarnings ({ "rawtypes", "unchecked" })
public class GamaSqlConnection extends GamaGisFile {
private static final String MYSQL = "mysql";
private static final String POSTGRES = "postgres";
private static final String POSTGIS = "postgis";
private static final String MSSQL = "sqlserver";
private static final String SQLITE = "spatialite";
private String dbtype = "";
private String host = "";
private String port = "";
private String database = "";
private String user = "";
private String passwd = "";
// Database object/ Database connection
private DataStore dataStore;
public GamaSqlConnection(final IScope scope) {
super(scope, FileUtils.constructAbsoluteFilePath(scope, "getfun.shp", false), 0);
setParams(scope);
}
private GamaSqlConnection(final IScope scope, final Map<String, Object> params) {
super(scope, FileUtils.constructAbsoluteFilePath(scope, "getfun.shp", false), 0);
setParams(params);
}
private void setParams(final IScope scope) {
setConnectionParameters(scope);
}
private void setParams(final Map<String, Object> params) {
setConnectionParameters(params);
}
private void setConnectionParameters(final IScope scope) {
final Map<String, Object> params = (Map<String, Object>) scope.getArg("params", IType.MAP);
this.dbtype = (String) params.get("dbtype");
this.host = (String) params.get("host");
this.port = (String) params.get("port");
this.database = (String) params.get("database");
this.user = (String) params.get("user");
this.passwd = (String) params.get("passwd");
}
private void setConnectionParameters(final Map<String, Object> params) {
this.dbtype = (String) params.get("dbtype");
this.host = (String) params.get("host");
this.port = (String) params.get("port");
this.database = (String) params.get("database");
this.user = (String) params.get("user");
this.passwd = (String) params.get("passwd");
}
// Connect connection parameters with connection attributes of the object
private Map<String, Object> createConnectionParams(final IScope scope) {
final Map<String, Object> connectionParameters = new HashMap<>();
if (dbtype.equalsIgnoreCase(GamaSqlConnection.POSTGRES) || dbtype.equalsIgnoreCase(GamaSqlConnection.POSTGIS)) {
connectionParameters.put("host", host);
connectionParameters.put("dbtype", dbtype);
connectionParameters.put("port", port);
connectionParameters.put("database", database);
connectionParameters.put("user", user);
connectionParameters.put("passwd", passwd);
// advanced
} else if (dbtype.equalsIgnoreCase(GamaSqlConnection.MYSQL)) {
connectionParameters.put(MySQLDataStoreFactory.DBTYPE.key, dbtype);
connectionParameters.put(JDBCDataStoreFactory.HOST.key, host);
connectionParameters.put(MySQLDataStoreFactory.PORT.key, Integer.valueOf(port));
connectionParameters.put(JDBCDataStoreFactory.DATABASE.key, database);
connectionParameters.put(JDBCDataStoreFactory.USER.key, user);
connectionParameters.put(JDBCDataStoreFactory.PASSWD.key, passwd);
} else if (dbtype.equalsIgnoreCase(GamaSqlConnection.MSSQL)) {
connectionParameters.put("host", host);
connectionParameters.put("dbtype", dbtype);
connectionParameters.put("port", port);
connectionParameters.put("database", database);
connectionParameters.put("user", user);
connectionParameters.put("passwd", passwd);
} else if (dbtype.equalsIgnoreCase(GamaSqlConnection.SQLITE)) {
final String DBRelativeLocation = FileUtils.constructAbsoluteFilePath(scope, database, true);
// String EXTRelativeLocation =
// GamaPreferences.LIB_SPATIALITE.value(scope).getPath();
connectionParameters.put("dbtype", dbtype);
connectionParameters.put("database", DBRelativeLocation);
}
return connectionParameters;
}
/*
* Create a connection to database with current connection parameter of the GamaSqlConnection object
*/
public DataStore Connect(final IScope scope) throws Exception {
final Map<String, Object> connectionParameters = createConnectionParams(scope);
DataStore dStore;
dStore = DataStoreFinder.getDataStore(connectionParameters); // get
// connection
// DEBUG.LOG("data store postgress:" + dStore);
if (dStore == null) throw new IOException("Can't connect to " + database);
return dStore;
}
/*
* Close the current connection of of the GamaSqlConnection object
*/
public void close(final IScope scope) throws GamaRuntimeException {
if (dataStore != null) {
dataStore.dispose();
} else
throw GamaRuntimeException.error("The connection to " + this.database + " is not opened ", scope);
}
public void setDataStore(final DataStore dataStore) {
this.dataStore = dataStore;
}
private void readTable(final IScope scope) {
final String tableName = (String) scope.getArg("table", IType.STRING);
final String filterStr = (String) scope.getArg("filter", IType.STRING);
readTable(scope, tableName, filterStr);
}
private void readTable(final IScope scope, final String tableName, final String filterStr) {
final IList list = getBuffer();
final QueryInfo queryInfo = new QueryInfo(scope, this.dataStore, tableName, filterStr);
try (SimpleFeatureIterator reader = queryInfo.getRecordSet().features()) {
final int size = queryInfo.getSize();
final Envelope3D env = queryInfo.getEnvelope();
int index = 0;
computeProjection(scope, env); // ??
// reader = store.getFeatureReader();
// final int i = 0;
while (reader.hasNext()) {
scope.getGui().getStatus(scope).setSubStatusCompletion(index++ / (double) size);
final Feature feature = reader.next();
// DEBUG.LOG("Record " + i++ + ": " +
// feature.getValue().toString());
Geometry g = (Geometry) feature.getDefaultGeometryProperty().getValue();
if (g != null && !g.isEmpty()) {
g = gis.transform(g);
list.add(new GamaGisGeometry(g, feature));
} else {
GAMA.reportError(scope, GamaRuntimeException.warning(
"GamaSqlConnection.fillBuffer; geometry could not be added : " + feature.getIdentifier(),
scope), false);
}
}
} catch (final Exception e) {
throw GamaRuntimeException.create(e, scope);
} finally {
scope.getGui().getStatus(scope).endSubStatus("Reading table " + tableName);
}
}
/**
* @see msi.gama.util.GamaFile#fillBuffer()
*/
@Override
protected void fillBuffer(final IScope scope) throws GamaRuntimeException {
if (getBuffer() != null) return;
setBuffer(GamaListFactory.<IShape> create(Types.GEOMETRY));
readTable(scope);
}
public void read(final IScope scope) {
fillBuffer(scope);
}
@Override
protected CoordinateReferenceSystem getOwnCRS(final IScope scope) {
return null;
}
// _________________________________________________________________
private static class QueryInfo {
private final int itemNumber; // Number of records
private final Envelope3D env;
private final SimpleFeatureCollection features; // data/recordsets
QueryInfo(final IScope scope, final DataStore dStore, final String tableName, final String filterStr) {
SimpleFeatureSource source = null;
SimpleFeatureCollection sfeatures = null; // Query data
final Map<String, String> attributes = new LinkedHashMap(); // Meta
// data
ReferencedEnvelope env = new ReferencedEnvelope();
CoordinateReferenceSystem crs = null;
int number = 0;
try {
source = dStore.getFeatureSource(tableName); // table
final Filter filter = ECQL.toFilter(filterStr); // create filter
// for read data
sfeatures = source.getFeatures(filter); // read data
try {
crs = source.getInfo().getCRS();
} catch (final Exception e) {
DEBUG.ERR("Ignored exception in ShapeInfo getCRS:" + e.getMessage());
}
env = source.getBounds();
if (crs != null) {
try {
env = env.transform(new ProjectionFactory().getTargetCRS(scope), true);
} catch (final Exception e) {}
}
number = sfeatures.size(); // get number of records
// get meta data
final java.util.List<AttributeDescriptor> att_list = source.getSchema().getAttributeDescriptors();
for (final AttributeDescriptor desc : att_list) {
String type;
if (desc.getType() instanceof GeometryType) {
type = "geometry";
} else {
type = Types.get(desc.getType().getBinding()).toString();
}
attributes.put(desc.getName().getLocalPart(), type);
}
} catch (final Exception e) {
DEBUG.ERR("Error in reading metadata of " + tableName);
} finally {
this.env = Envelope3D.of(env);
this.itemNumber = number; // number of records
this.features = sfeatures; // data
}
}
public int getSize() {
return itemNumber;
}
public Envelope3D getEnvelope() {
return env;
}
public SimpleFeatureCollection getRecordSet() {
return features;
}
}// end of class QueryInfo
@Override
protected SimpleFeatureCollection getFeatureCollection(final IScope scope) {
return null;
}
}