· 9 years ago · Dec 12, 2016, 11:54 AM
1public static void main(String[] args) throws Exception{
2 // launch(args);
3
4 File fileCSVParser = JFileDataStoreChooser.showOpenFile("csv",null);
5 if(fileCSVParser == null) System.exit(1);
6 List<List<String>> ParsedList = CSVParser(fileCSVParser.getAbsolutePath());
7 String querySQL = SqlQueryCreator(ParsedList);
8 SaveQueryToFile(querySQL);
9
10 //String test = "((-300120 7689960, -654360 7562040, 1640 7512840))";
11 //String geometry = test.replaceAll("[()]","");
12
13 //System.out.println(geometry);
14
15 File file = JFileDataStoreChooser.showOpenFile("csv",null);
16 if(file == null) System.exit(1);
17
18 java.util.List<SimpleFeature> list = new ArrayList<SimpleFeature>();
19 BufferedReader reader = new BufferedReader(new FileReader(file));
20 TYPE = null;
21 try {
22 String line = reader.readLine();
23
24 TYPE = createFeatureType2(line);
25
26 GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(null);
27
28 for (line = reader.readLine(); line != null; line = reader.readLine()) {
29 Object[] o = CreateObject(line,factory);
30 SimpleFeature feature = SimpleFeatureBuilder.build(TYPE, o, null);
31 list.add(feature);
32
33 }
34
35 } finally {
36 reader.close();
37 }
38 File newFile = getNewShapeFile(file);
39
40 ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
41
42 Map<String, Serializable> params = new HashMap<>();
43 params.put("url", newFile.toURI().toURL());
44 params.put("create spatial index", Boolean.TRUE);
45
46 ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
47
48 /*
49 * TYPE is used as a template to describe the file contents
50 */
51 newDataStore.createSchema(TYPE);
52
53 /*
54 * Write the features to the shapefile
55 */
56 Transaction transaction = new DefaultTransaction("create");
57
58 String typeName = newDataStore.getTypeNames()[0];
59 SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
60 SimpleFeatureType SHAPE_TYPE = featureSource.getSchema();
61 /*
62 * The Shapefile format has a couple limitations:
63 * - "the_geom" is always first, and used for the geometry attribute name
64 * - "the_geom" must be of type Point, MultiPoint, MuiltiLineString, MultiPolygon
65 * - Attribute names are limited in length
66 * - Not all data types are supported (example Timestamp represented as Date)
67 *
68 * Each data store has different limitations so check the resulting SimpleFeatureType.
69 */
70 System.out.println("SHAPE:"+SHAPE_TYPE);
71
72 if (featureSource instanceof SimpleFeatureStore)
73 {
74 SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
75 /*
76 * SimpleFeatureStore has a method to add features from a
77 * SimpleFeatureCollection object, so we use the ListFeatureCollection
78 * class to wrap our list of features.
79 */
80 SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, list);
81 featureStore.setTransaction(transaction);
82 try {
83 featureStore.addFeatures(collection);
84 transaction.commit();
85 } catch (Exception problem) {
86 problem.printStackTrace();
87 transaction.rollback();
88 } finally {
89 transaction.close();
90 }
91 System.exit(0); // success!
92 } else {
93 System.out.println(typeName + " does not support read/write access");
94 System.exit(1);
95 }
96 }
97
98 private static File getNewShapeFile(File csvFile) {
99 String path = csvFile.getAbsolutePath();
100 String newPath = path.substring(0, path.length() - 4) + ".shp";
101
102 JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
103 chooser.setDialogTitle("Save shapefile");
104 chooser.setSelectedFile(new File(newPath));
105
106 int returnVal = chooser.showSaveDialog(null);
107
108 if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
109 // the user cancelled the dialog
110 System.exit(0);
111 }
112
113 File newFile = chooser.getSelectedFile();
114 if (newFile.equals(csvFile)) {
115 System.out.println("Error: cannot replace " + csvFile);
116 System.exit(0);
117 }
118
119 return newFile;
120 }
121
122 private static Object[] CreateObject(String line, GeometryFactory factory)//,
123 //BufferedReader reader,
124 //java.util.List<SimpleFeature> list,
125 //SimpleFeature TYPE) throws Exception
126 {
127 //GeometryFactory factory = JTSFactoryFinder.getGeometryFactory(null);
128
129 //for (line = reader.readLine(); line != null; line = reader.readLine()) {
130 Object[] o = null;
131
132 if(geom == "the_geom:Point") {
133 String split[] = line.split("\\;");
134
135 //String name = split[0];
136 double latitude = Double.parseDouble(split[0]);
137 double longitude = Double.parseDouble(split[1]);
138
139 //System.out.println("" + latitude + " " + longitude);
140 o = new Object[split.length + 1];
141 //Object[] o = new Object[2];
142
143 for (int i = 1; i < o.length; i++) {
144 o[i] = split[i - 1];
145 }
146
147 o[0] = factory.createPoint(new Coordinate(longitude, latitude));
148 //o[1] = split[2];
149 //o[1] = name;
150
151 //SimpleFeature feature = SimpleFeatureBuilder.build(TYPE,o,null);
152 //list.add(feature);
153
154
155 //}
156
157 }
158 else if(geom == "the_geom:Polygon")
159 {
160 String split[] = line.split("\\;");
161 String geometry = split[0].replaceAll("[()]","");
162 o = new Object[split.length];
163 String[] points = geometry.split(",");
164
165 Coordinate[] coordinates = new Coordinate[points.length];
166
167 for(int i = 0; i<points.length; i++)
168 {
169 points[i] = points[i].replaceAll("^\\s+", "");
170
171 String[] coords = points[i].split(" ");
172
173 double x = Double.parseDouble(coords[0]);
174 double y = Double.parseDouble(coords[1]);
175 coordinates[i] = new Coordinate(x,y);
176 }
177
178 Polygon poly = factory.createPolygon(coordinates);
179 Polygon[] a = new Polygon[1];
180 a[0] = poly;
181 o[0] = factory.createMultiPolygon(a);
182 o[1] = split[1];
183
184
185 //System.out.println(geometry);
186 System.out.println(split[1]);
187 }
188 else if(geom == "the_geom:LineString")
189 {
190 String split[] = line.split("\\;");
191 String geometry = split[0].replaceAll("[()]","");
192 o = new Object[split.length];
193 String[] points = geometry.split(",");
194
195 Coordinate[] coordinates = new Coordinate[points.length];
196
197 for(int i = 0; i<points.length; i++)
198 {
199 points[i] = points[i].replaceAll("^\\s+", "");
200
201 String[] coords = points[i].split(" ");
202
203 double x = Double.parseDouble(coords[0]);
204 double y = Double.parseDouble(coords[1]);
205 coordinates[i] = new Coordinate(x,y);
206 }
207
208 //Polygon poly = factory.createPolygon(coordinates);
209 //Polygon[] a = new Polygon[1];
210 //a[0] = poly;
211 o[0] = factory.createLineString(coordinates);
212 o[1] = split[1];
213
214
215 //System.out.println(geometry);
216 System.out.println(split[1]);
217 }
218
219
220 return o;
221 }
222
223 /*
224 private static SimpleFeatureType createFeatureType(String[] headers) {
225
226 SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
227 builder.setName("Location");
228 builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
229
230 if(headers[0] == "the_geom:Polygon") builder.add("the_geom", Polygon.class);
231 else if(headers[0] == "the_geom:LineString") builder.add("the_geom", LineString.class);
232 // add attributes in order
233 else builder.add("the_geom", Point.class);
234 builder.length(15).add("Name", String.class); // <- 15 chars width for name field
235 builder.add("number",Integer.class);
236
237 // build the type
238 final SimpleFeatureType LOCATION = builder.buildFeatureType();
239
240
241 //stringBuilder.append("the_geom:Geometry,");
242
243 for (String header : headers) {
244 //System.out.println(header);
245 //stringBuilder.append("").append(header).append(":String,");
246
247 }
248
249 //System.out.println(stringBuilder);
250
251 //TYPE = DataUtilities.createType("Location", stringBuilder.substring(0, stringBuilder.toString().length() - 1));
252
253 return LOCATION;
254 }
255 */
256
257 private static SimpleFeatureType createFeatureType2(String line) throws Exception
258 {
259 StringBuilder stringBuilder = new StringBuilder();
260
261
262
263
264 String[] headers = line.split("\\;");
265 System.out.println(geom);
266 if(headers[0].equals("the_geom:Polygon")) {
267 //System.out.println("bomba");
268 geom = "the_geom:Polygon";
269 }
270 else if(headers[0].equals("the_geom:LineString")) {
271
272 geom = "the_geom:LineString";
273 }
274 else {
275 geom = "the_geom:Point";
276
277 }
278 System.out.println(geom + " " + headers[0]);
279 //System.out.println(headers[0]);
280 stringBuilder.append(geom + ",");
281
282 for (String header : headers) {
283 if(header == headers[0]) continue;
284 System.out.println(header);
285 stringBuilder.append("").append(header).append(":String,");
286 }
287 System.out.println(stringBuilder);
288 //System.out.println(stringBuilder);
289
290 SimpleFeatureType TYPE = DataUtilities.createType("Location", stringBuilder.substring(0, stringBuilder.toString().length() - 1));
291
292
293 return TYPE;
294 }
295
296 public static List<List<String>> CSVParser(String path)
297 {
298 String csvFile = path;
299 BufferedReader br = null;
300 String line = "";
301 String cvsSplitBy = ";";
302 List<List<String>> listToParse = new ArrayList<List<String>>();
303 try {
304
305 br = new BufferedReader(new FileReader(csvFile));
306 while ((line = br.readLine()) != null)
307 {
308 List<String> arrayTemp =new ArrayList<>();
309 String[] country = line.split(cvsSplitBy);
310 for(int i = 0;i<country.length;i++)
311 {
312 arrayTemp.add(country[i]);
313 }
314 listToParse.add(arrayTemp);
315 }
316
317 } catch (FileNotFoundException e) {
318 e.printStackTrace();
319 } catch (IOException e) {
320 e.printStackTrace();
321 } finally {
322 if (br != null) {
323 try {
324 br.close();
325 } catch (IOException e) {
326 e.printStackTrace();
327 }
328 }
329 }
330 return listToParse;
331 }
332
333 public static String SqlQueryCreator(List<List<String>> ParsedList)
334 {
335 String sqlCommand = "\n" +
336 "CREATE TABLE IF NOT EXISTS PointSQL (\n" +
337 " id SERIAL PRIMARY KEY,\n" +
338 " geometry GEOMETRY,\n" +
339 " ELEV int\n" +
340 ");\n" +
341 "\n" +
342 "CREATE TABLE IF NOT EXISTS LineSQL (\n" +
343 " id SERIAL PRIMARY KEY,\n" +
344 " geometry GEOMETRY,\n" +
345 " ELEV int\n" +
346 ");\n" +
347 "\n" +
348 "CREATE TABLE IF NOT EXISTS GeoSQL (\n" +
349 " id SERIAL PRIMARY KEY,\n" +
350 " geometry GEOMETRY,\n" +
351 " ELEV int\n" +
352 ");\n\n";
353 if(ParsedList.size() > 0)
354 {
355 for(int i=1; i<ParsedList.size(); i++)
356 {
357 String temp = ParsedList.get(0).get(0);
358 if(ParsedList.get(0).get(0).equals("X"))
359 {
360 String sqlTemp = "insert into PointSQL(geometry,ELEV) values(ST_GeomFromText('POINT("+ ParsedList.get(i).get(0) +" "+ ParsedList.get(i).get(1) +")'), "+ ParsedList.get(i).get(2) +");\n";
361 sqlCommand += sqlTemp;
362 }
363 else if(ParsedList.get(0).get(0).equals("the_geom:LineString"))
364 {
365 String sqlTemp = "insert into LineSQL(geometry,ELEV) values(1, ST_GeomFromText('LINESTRING"+ ParsedList.get(i).get(0) +"'),"+ ParsedList.get(i).get(1) +");\n";
366 sqlCommand += sqlTemp;
367 }
368 else if(ParsedList.get(0).get(0).equals("the_geom:Polygon"))
369 {
370 String sqlTemp = "insert into GeoSQL(geometry,ELEV) values(1, ST_GeomFromText('polygon"+ ParsedList.get(i).get(0) +"'),"+ ParsedList.get(i).get(1) +");\n";
371 sqlCommand += sqlTemp;
372 }
373 }
374 }
375 return sqlCommand;
376 }
377
378 public static void SaveQueryToFile(String text)
379 {
380 try
381 {
382 FileUtils.writeStringToFile(new File("sqlQuery.sql"), text);
383 } catch (IOException e)
384 {
385 e.printStackTrace();
386 }
387 }
388
389}