Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.55 KB | None | 0 0
  1. import java.awt.event.ActionEvent;
  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.io.Serializable;
  5. import java.net.URI;
  6. import java.net.URL;
  7.  
  8. import java.util.HashMap;
  9. import java.util.Map;
  10. import java.util.Set;
  11.  
  12. import javax.swing.Action;
  13. import javax.swing.JButton;
  14. import javax.swing.JOptionPane;
  15. import javax.swing.JToolBar;
  16. import javax.swing.SwingWorker;
  17.  
  18. import org.geotools.data.DataStore;
  19.  
  20. import org.geotools.data.DataStoreFactorySpi;
  21. import org.geotools.data.DefaultTransaction;
  22. import org.geotools.data.FeatureWriter;
  23. import org.geotools.data.FileDataStore;
  24. import org.geotools.data.FileDataStoreFinder;
  25. import org.geotools.data.Query;
  26. import org.geotools.data.Transaction;
  27. import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  28. import org.geotools.data.simple.SimpleFeatureCollection;
  29. import org.geotools.data.simple.SimpleFeatureIterator;
  30. import org.geotools.data.simple.SimpleFeatureSource;
  31. import org.geotools.data.simple.SimpleFeatureStore;
  32. import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
  33. import org.geotools.geometry.jts.JTS;
  34. import org.geotools.geometry.jts.ReferencedEnvelope;
  35. import org.geotools.map.FeatureLayer;
  36. import org.geotools.map.Layer;
  37. import org.geotools.map.MapContent;
  38. import org.geotools.referencing.CRS;
  39. import org.geotools.referencing.ReferencingFactoryFinder;
  40. import org.geotools.referencing.factory.gridshift.GridShiftLocator;
  41. import org.geotools.styling.SLD;
  42. import org.geotools.styling.Style;
  43. import org.geotools.swing.JMapFrame;
  44. import org.geotools.swing.JProgressWindow;
  45. import org.geotools.swing.action.SafeAction;
  46. import org.geotools.swing.data.JFileDataStoreChooser;
  47. import org.locationtech.jts.geom.Envelope;
  48. import org.opengis.feature.Feature;
  49. import org.opengis.feature.FeatureVisitor;
  50. import org.opengis.feature.simple.SimpleFeature;
  51. import org.opengis.feature.simple.SimpleFeatureType;
  52. import org.opengis.feature.type.FeatureType;
  53. import org.opengis.referencing.crs.CoordinateReferenceSystem;
  54. import org.opengis.referencing.operation.MathTransform;
  55. import org.opengis.util.ProgressListener;
  56.  
  57. import com.vividsolutions.jts.geom.Geometry;
  58.  
  59. public class CRSLab {
  60.  
  61. private File sourceFile;
  62. private SimpleFeatureSource featureSource;
  63. private MapContent map;
  64.  
  65. public static void main(String[] args) throws Exception {
  66. CRSLab lab = new CRSLab();
  67. lab.displayShapefile();
  68. }
  69.  
  70. // docs end main
  71. /**
  72. * This method:
  73. * <ol type="1">
  74. * <li>Prompts the user for a shapefile to display
  75. * <li>Creates a JMapFrame with custom toolbar buttons
  76. * <li>Displays the shapefile
  77. * </ol>
  78. */
  79. // docs start display
  80. private void displayShapefile() throws Exception {
  81. sourceFile = JFileDataStoreChooser.showOpenFile("shp", null);
  82. if (sourceFile == null) {
  83. return;
  84. }
  85. FileDataStore store = FileDataStoreFinder.getDataStore(sourceFile);
  86. featureSource = store.getFeatureSource();
  87.  
  88. // Create a map context and add our shapefile to it
  89. map = new MapContent();
  90. Style style = SLD.createSimpleStyle(featureSource.getSchema());
  91. Layer layer = new FeatureLayer(featureSource, style);
  92. map.layers().add(layer);
  93.  
  94. // Create a JMapFrame with custom toolbar buttons
  95. JMapFrame mapFrame = new JMapFrame(map);
  96. mapFrame.enableToolBar(true);
  97. mapFrame.enableStatusBar(true);
  98.  
  99. JToolBar toolbar = mapFrame.getToolBar();
  100. toolbar.addSeparator();
  101. toolbar.add(new JButton(new ValidateGeometryAction()));
  102. toolbar.add(new JButton(new ExportShapefileAction()));
  103.  
  104. // Display the map frame. When it is closed the application will exit
  105. mapFrame.setSize(800, 600);
  106. mapFrame.setVisible(true);
  107. }
  108. // docs end display
  109.  
  110.  
  111. // docs start export
  112. private void exportToShapefile() throws Exception {
  113. SimpleFeatureType schema = featureSource.getSchema();
  114. JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
  115. chooser.setDialogTitle("Save reprojected shapefile");
  116. chooser.setSaveFile(sourceFile);
  117. int returnVal = chooser.showSaveDialog(null);
  118. if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
  119. return;
  120. }
  121. File file = chooser.getSelectedFile();
  122. if (file.equals(sourceFile)) {
  123. JOptionPane.showMessageDialog(null, "Cannot replace " + file);
  124. return;
  125. }
  126.  
  127. // set up the math transform used to process the data
  128. CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
  129. CoordinateReferenceSystem worldCRS = CRS.decode("EPSG:32056", true);// map.getCoordinateReferenceSystem();
  130. boolean lenient = true; // allow for some error due to different datums
  131. MathTransform transform = CRS.findMathTransform(dataCRS, worldCRS, lenient);
  132.  
  133. // grab all features
  134. SimpleFeatureCollection featureCollection = featureSource.getFeatures();
  135.  
  136. // And create a new Shapefile with a slight modified schema
  137. DataStoreFactorySpi factory = new ShapefileDataStoreFactory();
  138. Map<String, Serializable> create = new HashMap<String, Serializable>();
  139. create.put("url", file.toURI().toURL());
  140. create.put("create spatial index", Boolean.TRUE);
  141. DataStore dataStore = factory.createNewDataStore(create);
  142. SimpleFeatureType featureType = SimpleFeatureTypeBuilder.retype(schema, worldCRS);
  143. dataStore.createSchema(featureType);
  144. String createdName = dataStore.getTypeNames()[0];
  145. // carefully open an iterator and writer to process the results
  146. Transaction transaction = new DefaultTransaction("Reproject");
  147. FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(createdName,
  148. transaction);
  149. SimpleFeatureIterator iterator = featureCollection.features();
  150. try {
  151. int counter = 0;
  152. while (iterator.hasNext()) {
  153. // copy the contents of each feature and transform the geometry
  154. SimpleFeature feature = iterator.next();
  155. SimpleFeature copy = writer.next();
  156.  
  157. org.locationtech.jts.geom.Geometry geometry = (org.locationtech.jts.geom.Geometry) feature
  158. .getDefaultGeometry();
  159. org.locationtech.jts.geom.Geometry geometry2 = JTS.transform(geometry, transform);
  160. System.out.println(geometry.isSimple() && geometry2.isSimple());
  161. // if (geometry2.isValid()) {
  162. copy.setAttributes(feature.getAttributes());
  163. counter++;
  164. copy.setDefaultGeometry(geometry2);
  165. writer.write();
  166. // }
  167. }
  168. transaction.commit();
  169. System.out.println("valid geometries : " + counter);
  170. JOptionPane.showMessageDialog(null, "Export to shapefile complete");
  171. } catch (Exception problem) {
  172. problem.printStackTrace();
  173. transaction.rollback();
  174. JOptionPane.showMessageDialog(null, "Export to shapefile failed");
  175. } finally {
  176. writer.close();
  177. iterator.close();
  178. transaction.close();
  179. }
  180. }
  181. // docs end export
  182.  
  183. // docs start validate
  184. private int validateFeatureGeometry(ProgressListener progress) throws Exception {
  185. final SimpleFeatureCollection featureCollection = featureSource.getFeatures();
  186.  
  187. // Rather than use an iterator, create a FeatureVisitor to check each
  188. // fature
  189. class ValidationVisitor implements FeatureVisitor {
  190. public int numInvalidGeometries = 0;
  191.  
  192. public void visit(Feature f) {
  193. SimpleFeature feature = (SimpleFeature) f;
  194. Geometry geom = (Geometry) feature.getDefaultGeometry();
  195. if (geom != null && !geom.isValid()) {
  196. numInvalidGeometries++;
  197. System.out.println("Invalid Geoemtry: " + feature.getID());
  198. }
  199. }
  200. }
  201.  
  202. ValidationVisitor visitor = new ValidationVisitor();
  203.  
  204. // Pass visitor and the progress bar to feature collection
  205. featureCollection.accepts(visitor, progress);
  206. return visitor.numInvalidGeometries;
  207. }
  208. // docs end validate
  209.  
  210. // docs start export action
  211. class ExportShapefileAction extends SafeAction {
  212. ExportShapefileAction() {
  213. super("Export...");
  214. putValue(Action.SHORT_DESCRIPTION, "Export using current crs");
  215. }
  216.  
  217. public void action(ActionEvent e) throws Throwable {
  218. exportToShapefile();
  219. }
  220. }
  221. // docs end export action
  222.  
  223. /**
  224. * This class performs the task of checking that the Geometry of each
  225. * feature is topologically valid and reports on the results. It also
  226. * supplies the name and tool tip.
  227. */
  228. // docs start validate action
  229. class ValidateGeometryAction extends SafeAction {
  230. ValidateGeometryAction() {
  231. super("Validate geometry");
  232. putValue(Action.SHORT_DESCRIPTION, "Check each geometry");
  233. }
  234.  
  235. public void action(ActionEvent e) throws Throwable {
  236. int numInvalid = validateFeatureGeometry(null);
  237. String msg;
  238. if (numInvalid == 0) {
  239. msg = "All feature geometries are valid";
  240. } else {
  241. msg = "Invalid geometries: " + numInvalid;
  242. }
  243. JOptionPane.showMessageDialog(null, msg, "Geometry results", JOptionPane.INFORMATION_MESSAGE);
  244. }
  245. }
  246. // docs end validate action
  247.  
  248. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement