001: package org.geotools.demo;
002:
003: import java.io.BufferedReader;
004: import java.io.File;
005: import java.io.FileNotFoundException;
006: import java.io.FileReader;
007: import java.util.HashMap;
008: import java.util.Map;
009:
010: import javax.swing.JFileChooser;
011: import javax.swing.filechooser.FileFilter;
012:
013: import org.geotools.data.DataStoreFactorySpi;
014: import org.geotools.data.DataUtilities;
015: import org.geotools.data.DefaultTransaction;
016: import org.geotools.data.FeatureStore;
017: import org.geotools.data.Transaction;
018: import org.geotools.data.shapefile.ShapefileDataStore;
019: import org.geotools.data.shapefile.ShapefileDataStoreFactory;
020: import org.geotools.feature.AttributeType;
021: import org.geotools.feature.AttributeTypeFactory;
022: import org.geotools.feature.Feature;
023: import org.geotools.feature.FeatureCollection;
024: import org.geotools.feature.FeatureCollections;
025: import org.geotools.feature.FeatureType;
026: import org.geotools.feature.FeatureTypeBuilder;
027: import org.geotools.feature.SchemaException;
028: import org.geotools.referencing.crs.DefaultGeographicCRS;
029:
030: import com.vividsolutions.jts.geom.Coordinate;
031: import com.vividsolutions.jts.geom.GeometryFactory;
032: import com.vividsolutions.jts.geom.Point;
033:
034: public class Csv2Shp {
035:
036: /**
037: * This example takes a CSV file and produces a shape file.
038: * <p>
039: * The interesting part of this example is the use of a Factory when
040: * creating objects.
041: *
042: * <pre><code>
043: * GeometryFactory factory = new GeometryFactory();
044: * Point point = factory.createPoint(new Coordinate(longitude, latitude));
045: * </code></pre>
046: *
047: * These two classes come from the JTS Topology Suite responsible for the
048: * "rocket science" aspect of GIS - determining the relationships between
049: * geometry shapes.
050: *
051: * @param args
052: * @throws Exception
053: */
054: public static void main(String[] args) throws Exception {
055: File file = getCSVFile(args);
056: FeatureType type = createFeatureType();
057:
058: FeatureCollection collection = FeatureCollections
059: .newCollection();
060: BufferedReader reader = new BufferedReader(new FileReader(file));
061: GeometryFactory geometryFactory = new GeometryFactory();
062: try {
063: String line = reader.readLine();
064: System.out.println("Header: " + line);
065: for (line = reader.readLine(); line != null; line = reader
066: .readLine()) {
067: String split[] = line.split("\\,");
068: double longitude = Double.parseDouble(split[0]);
069: double latitude = Double.parseDouble(split[1]);
070: String name = split[2];
071:
072: Coordinate coordinate = new Coordinate(longitude,
073: latitude);
074: Point point = geometryFactory.createPoint(coordinate);
075: Feature feature = type.create(new Object[] { point,
076: name });
077:
078: collection.add(feature);
079: }
080: } finally {
081: reader.close();
082: }
083: File newFile = getNewShapeFile(file);
084:
085: DataStoreFactorySpi factory = new ShapefileDataStoreFactory();
086:
087: Map create = new HashMap();
088: create.put("url", newFile.toURI().toURL());
089: create.put("create spatial index", Boolean.TRUE);
090:
091: ShapefileDataStore newDataStore = (ShapefileDataStore) factory
092: .createNewDataStore(create);
093: newDataStore.createSchema(type);
094: newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
095:
096: Transaction transaction = new DefaultTransaction("create");
097: String typeName = newDataStore.getTypeNames()[0];
098: FeatureStore featureStore = (FeatureStore) newDataStore
099: .getFeatureSource(typeName);
100: featureStore.setTransaction(transaction);
101: try {
102: featureStore.addFeatures(collection);
103: transaction.commit();
104: } catch (Exception problem) {
105: problem.printStackTrace();
106: transaction.rollback();
107: } finally {
108: transaction.close();
109: }
110: System.exit(0);
111: }
112:
113: /**
114: * This this method we Create a "Location" feature type consisting
115: * of a location (ie a Point) and a name (ie a String).
116: * <p>
117: * This implementation uses the DataUtilities class as a nice readable short-cut.
118: * There are several problems with this result:
119: * <ul>
120: * <li>The name "Location" is unqualified (only important if you are are working
121: * with lots of conflicting GML files)
122: * <li>The "location" Point does not have a CoordinateReferenceSystem associated with
123: * it - this limits what you can do with the data (no reprojection or drawing)
124: * <li>The "name" String does not have a fixed length (so when we create a shapefile
125: * it will default to 255 characters (a really big DBF file)
126: * <ul>
127: * Please look at AttributeTypeFactory and FeatureTypeBuilder to see how to resolve
128: * these issues.
129: *
130: * @return Location FeatureType
131: * @throws SchemaException
132: */
133: private static FeatureType createFeatureType()
134: throws SchemaException {
135: FeatureType schema = DataUtilities.createType("Landmarks",
136: "location:Point,name:String");
137: return schema;
138: }
139:
140: /**
141: * This method uses AttributeTypeFactory and FeatureTypeBuilder to
142: * create the "Location" FeatureType we are going to export.
143: *
144: * @return Location FeatureType
145: * @throws Exception
146: */
147: public FeatureType createFeatureType2() throws Exception {
148: final AttributeType LOCATION = AttributeTypeFactory
149: .newAttributeType("Location", Point.class, false, 0,
150: null, DefaultGeographicCRS.WGS84);
151: final AttributeType NAME = AttributeTypeFactory
152: .newAttributeType("Name", // name of attirbute type
153: String.class, // attribute type binding
154: true, // nillable
155: 15 // 15 characters allowed
156: );
157:
158: FeatureTypeBuilder builder = FeatureTypeBuilder
159: .newInstance("Landmarks");
160: builder.addType(LOCATION);
161: builder.addType(NAME);
162:
163: FeatureType schema = builder.getFeatureType();
164: return schema;
165: }
166:
167: /**
168: * This method takes the original csv file name as a reference point
169: * and prompts the user for a new filename.
170: * @param origional The origional csv file
171: * @return filename provided by the user
172: */
173: private static File getNewShapeFile(File origional) {
174: String path = origional.getAbsolutePath();
175: String newPath = path.substring(0, path.length() - 4) + ".shp";
176:
177: JFileChooser chooser = new JFileChooser();
178: chooser.setDialogTitle("Save shapefile");
179: chooser.setSelectedFile(new File(newPath));
180: chooser.setFileFilter(new FileFilter() {
181: public boolean accept(File f) {
182: return f.isDirectory() || f.getPath().endsWith("shp")
183: || f.getPath().endsWith("SHP");
184: }
185:
186: public String getDescription() {
187: return "Shapefiles";
188: }
189: });
190: int returnVal = chooser.showSaveDialog(null);
191: if (returnVal != JFileChooser.APPROVE_OPTION) {
192: System.exit(0);
193: }
194: File newFile = chooser.getSelectedFile();
195: return newFile;
196: }
197:
198: private static File getCSVFile(String[] args)
199: throws FileNotFoundException {
200: File file;
201: if (args.length == 0) {
202: JFileChooser chooser = new JFileChooser();
203: chooser.setDialogTitle("Open CSV file");
204: chooser.setFileFilter(new FileFilter() {
205: public boolean accept(File f) {
206: return f.isDirectory()
207: || f.getPath().endsWith("csv")
208: || f.getPath().endsWith("CSV");
209: }
210:
211: public String getDescription() {
212: return "Comma Seperated Value";
213: }
214: });
215: int returnVal = chooser.showOpenDialog(null);
216:
217: if (returnVal != JFileChooser.APPROVE_OPTION) {
218: System.exit(0);
219: }
220: file = chooser.getSelectedFile();
221:
222: System.out.println("Opening CVS file: " + file.getName());
223: } else {
224: file = new File(args[0]);
225: }
226: if (!file.exists()) {
227: throw new FileNotFoundException(file.getAbsolutePath());
228: }
229: return file;
230: }
231:
232: }
|