Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.sqlite / org.gvsig.sqlite.provider / src / main / java / org / gvsig / sqlite / dal / geopackage / GeopackageSpatialRefSys.java @ 47579

History | View | Annotate | Download (11.2 KB)

1
/*
2
 * To change this license header, choose License Headers in Project Properties.
3
 * To change this template file, choose Tools | Templates
4
 * and open the template in the editor.
5
 */
6
package org.gvsig.sqlite.dal.geopackage;
7

    
8
import java.nio.charset.StandardCharsets;
9
import java.sql.ResultSet;
10
import java.sql.SQLException;
11
import java.sql.Statement;
12
import java.util.logging.Level;
13
import java.util.regex.Matcher;
14
import java.util.regex.Pattern;
15
import org.apache.commons.io.IOUtils;
16
import org.apache.commons.lang3.math.NumberUtils;
17
import org.cresques.cts.IProjection;
18
import org.gvsig.fmap.dal.store.jdbc2.JDBCConnection;
19
import org.gvsig.fmap.dal.store.jdbc2.JDBCUtils;
20
import org.gvsig.fmap.dal.store.jdbc2.spi.JDBCSQLBuilderBase;
21
import org.gvsig.sqlite.dal.SQLiteHelper;
22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24

    
25
/**
26
 *
27
 * @author fdiaz
28
 */
29
public class GeopackageSpatialRefSys {
30

    
31
    final static protected Logger LOGGER = LoggerFactory.getLogger(GeopackageSpatialRefSys.class);
32
//    private static JsonArray spatial_ref_sys = null;
33

    
34
    private String srs_name;
35
    private int srs_id;
36
    private String organization;
37
    private int organization_coordsys_id;
38
    private String definition;
39
    private String description;
40

    
41
    public GeopackageSpatialRefSys(IProjection projection) {
42
        if (!search(projection)) {
43
            if (projection.isProjected()) {
44
                definition = "undefined";
45
                description = "undefined cartesian coordinate reference system";
46
                organization = "NONE";
47
                organization_coordsys_id = -1;
48
                srs_id = -1;
49
                srs_name = "Undefined cartesian SRS";
50
            } else {
51
                definition = "undefined";
52
                description = "undefined geographic coordinate reference system";
53
                organization = "NONE";
54
                organization_coordsys_id = 0;
55
                srs_id = 0;
56
                srs_name = "Undefined geographic SRS";
57
            }
58
        }
59
    }
60

    
61
//    private boolean search_json(IProjection projection) {
62
//        if(spatial_ref_sys == null) {
63
//            InputStream res = GeopackageSpatialRefSys.class.getResourceAsStream("....gpkg.....");
64
//            spatial_ref_sys = Json.createArray(res);
65
//        }
66
//        String projFullCode = projection.getFullCode();
67
//        for (JsonValue item : spatial_ref_sys) {
68
//            String org = ((JsonObject)item).getString("organization", null);
69
//            int srsId = ((JsonObject)item).getInt("organization_coordsys_id", Integer.MIN_VALUE);
70
//            if(org != null && srsId != Integer.MIN_VALUE && StringUtils.startsWith(projFullCode, org+":"+srsId)){
71
//                setOrganization(org);
72
//                setOrganizationCoordsysId(srsId);
73
//                setSrsName(((JsonObject)item).getString("srs_name", null));
74
//                setDefinition(((JsonObject)item).getString("definition", null));
75
//                setDescription(((JsonObject)item).getString("description", null));
76
//            }
77
//            return true;
78
//        }
79
//        return false;
80
//    }
81
    private boolean search(IProjection projection) {
82
        String abrev = "UNKNOWN";
83
        try {
84
            abrev = projection.getAbrev();
85
            String[] ss = abrev.split(":");
86
            String authority = ss[0];
87
            int authorityCode = NumberUtils.toInt(ss[1], Integer.MIN_VALUE);
88
            if (authorityCode == Integer.MIN_VALUE) {
89
                return false;
90
            }
91
            String resourceName = "/org/gvsig/sqlite/dal/epsg_crs_wkt/" + authority + "-CRS-" + authorityCode + ".wkt";
92
            String wkt = IOUtils.resourceToString(resourceName, StandardCharsets.UTF_8);
93
            Pattern pattern = Pattern.compile("[A-Z]+\\[\\s*\"(?<srsname>[^\"]*)\".*");
94
            Matcher matcher = pattern.matcher(wkt);
95
            if (matcher != null && matcher.matches()) {
96
                setSrsName(matcher.group("srsname"));
97
            } else {
98
                setSrsName(abrev);
99
            }
100
            setDefinition(wkt);
101
            setOrganization(authority);
102
            setOrganizationCoordsysId(authorityCode);
103
            setSrsId(authorityCode);
104
            setDescription("");
105

    
106
            return true;
107
        } catch (Exception ex) {
108
            LOGGER.debug("Can't search projection '" + abrev + "'", ex);
109
            return false;
110
        }
111
    }
112

    
113
    public void setSrsName(String srs_name) {
114
        this.srs_name = srs_name;
115
    }
116

    
117
    public String getSrsName() {
118
        return srs_name;
119
    }
120

    
121
    public void setSrsId(int srs_id) {
122
        this.srs_id = srs_id;
123
    }
124

    
125
    public int getSrsId() {
126
        return srs_id;
127
    }
128

    
129
    public void setOrganization(String organization) {
130
        this.organization = organization;
131
    }
132

    
133
    public String getOrganization() {
134
        return organization;
135
    }
136

    
137
    public void setOrganizationCoordsysId(int organization_coordsys_id) {
138
        this.organization_coordsys_id = organization_coordsys_id;
139
    }
140

    
141
    public int getOrganizationCoordsysId() {
142
        return organization_coordsys_id;
143
    }
144

    
145
    public void setDefinition(String definition) {
146
        this.definition = definition;
147
    }
148

    
149
    public String getDefinition() {
150
        return definition;
151
    }
152

    
153
    public void setDescription(String description) {
154
        this.description = description;
155
    }
156

    
157
    public String getDescription() {
158
        return description;
159
    }
160

    
161
    public boolean exists(JDBCConnection conn) {
162
        Statement sta = null;
163
        ResultSet rs = null;
164
        try {
165
            sta = conn.createStatement();
166
            String sql = String.format(
167
                    "Select * from gpkg_spatial_ref_sys where organization = '%s' and organization_coordsys_id = %d",
168
                    getOrganization(),
169
                    getOrganizationCoordsysId()
170
            );
171
            rs = JDBCUtils.executeQuery(sta, sql);
172
            return rs.next();
173
        } catch (Exception ex) {
174
            LOGGER.debug("Can't verify if exists the spatial_ref_sys '" + getOrganization() + ":" + getOrganizationCoordsysId() + "' in BD.", ex);
175
        } finally {
176
            JDBCUtils.closeQuietly(rs);
177
            JDBCUtils.closeQuietly(sta);
178
        }
179
        return false;
180
    }
181

    
182
    public void save(SQLiteHelper helper) {
183
        JDBCConnection conn = null;
184
        ResultSet tables = null;
185
        Statement sta = null;
186
        try {
187
            conn = helper.getConnection();
188
            conn.begin();
189
            sta = conn.createStatement();
190
            JDBCSQLBuilderBase sqlBuilder = helper.createSQLBuilder();
191
            StringBuilder builder = new StringBuilder();
192
            if (!exists(conn)) {
193
                tables = conn.getMetaData().getTables(null, null, "gpkg_spatial_ref_sys", null);
194
                if (!tables.next()) {
195
                    createGpkgSpatialRefSysTable(conn);
196
                }
197
                builder.append("INSERT INTO gpkg_spatial_ref_sys (srs_name, srs_id, organization, organization_coordsys_id, definition, description) VALUES (");
198
                builder.append(sqlBuilder.as_string(getSrsName()));
199
                builder.append(",");
200
                builder.append(getSrsId());
201
                builder.append(",");
202
                builder.append(sqlBuilder.as_string(getOrganization()));
203
                builder.append(",'");
204
                builder.append(getOrganizationCoordsysId());
205
                builder.append("',");
206
                builder.append(sqlBuilder.as_string(getDefinition()));
207
                builder.append(",");
208
                builder.append(sqlBuilder.as_string(getDescription()));
209
                builder.append(")");
210
                JDBCUtils.execute(sta, builder.toString());
211
//            } else {
212
//                builder.append("UPDATE gpkg_spatial_ref_sys SET ");
213
//                builder.append("srs_name = ");
214
//                builder.append(sqlBuilder.as_string(getSrsName()));
215
//                builder.append(", srs_id = ");
216
//                builder.append(getSrsId());
217
//                builder.append(", definition = '");
218
//                builder.append(sqlBuilder.as_string(getDefinition()));
219
//                builder.append(", description = ");
220
//                builder.append(sqlBuilder.as_string(getDescription()));
221
//                builder.append(" WHERE organization = ");
222
//                builder.append(sqlBuilder.as_string(getOrganization()));
223
//                builder.append(" and organization_coordsys_id = ");
224
//                builder.append(getOrganizationCoordsysId());
225
//                builder.append(";");
226
//                JDBCUtils.executeUpdate(sta, builder.toString());
227
            }
228
        } catch (Exception ex2) {
229
            throw new GeopackageException(
230
                    "Can't save the spatial_ref_sys '" + getOrganization() + ":" + getOrganizationCoordsysId() + "' in BD.", ex2);
231
        } finally {
232
            if(conn != null) {
233
                try {
234
                    conn.commit();
235
                } catch (SQLException ex) {
236
                    throw new GeopackageException(
237
                    "Can't save the spatial_ref_sys '" + getOrganization() + ":" + getOrganizationCoordsysId() + "' in BD.", ex);
238
                }
239
            }
240
            JDBCUtils.closeQuietly(sta);
241
            JDBCUtils.closeQuietly(tables);
242
            JDBCUtils.closeQuietly(sta);
243
        }
244
    }
245

    
246
    public boolean load(JDBCConnection conn) throws SQLException {
247
        Statement sta = null;
248
        ResultSet rs = null;
249
        try {
250
            sta = conn.createStatement();
251
            String sql = String.format(
252
                    "Select * from gpkg_spatial_ref_sys where organization = '%s' and organization_coordsys_id = %d",
253
                    getOrganization(),
254
                    getOrganizationCoordsysId()
255
            );
256

    
257
            rs = sta.executeQuery(sql);
258
            if (rs.next()) {
259
                this.setSrsName(rs.getString("srs_name"));
260
                this.setSrsId(rs.getInt("srs_id"));
261
                this.setDefinition(rs.getString("definition"));
262
                this.setDescription(rs.getString("description"));
263
                return true;
264
            } else {
265
                return false;
266
            }
267
        } catch (SQLException ex) {
268
            LOGGER.warn("Can't load exists the spatial_ref_sys '" + getOrganization() + ":" + getOrganizationCoordsysId() + "' in BD.", ex);
269
        } finally {
270
            if (rs != null) {
271
                rs.close();
272
            }
273
            if (sta != null) {
274
                sta.close();
275
            }
276
        }
277
        return false;
278

    
279
    }
280

    
281
    public static boolean createGpkgSpatialRefSysTable(JDBCConnection conn) {
282
        try (Statement sta = conn.createStatement()) {
283
            String sql = "CREATE TABLE \"gpkg_spatial_ref_sys\" (\n"
284
                    + "        \"srs_name\"        TEXT NOT NULL,\n"
285
                    + "        \"srs_id\"        INTEGER NOT NULL,\n"
286
                    + "        \"organization\"        TEXT NOT NULL,\n"
287
                    + "        \"organization_coordsys_id\"        INTEGER NOT NULL,\n"
288
                    + "        \"definition\"        TEXT NOT NULL,\n"
289
                    + "        \"description\"        TEXT,\n"
290
                    + "        PRIMARY KEY(\"srs_id\")\n"
291
                    + ");";
292

    
293
            JDBCUtils.execute(sta, sql);
294
            return true;
295
        } catch (SQLException ex) {
296
            LOGGER.warn("Can't create spatial_ref_sys table'", ex);
297
        }
298
        return false;
299

    
300
    }
301

    
302
}