/gazetteer/src/main/java/org/ala/rest/Intersector.java

http://alageospatialportal.googlecode.com/ · Java · 207 lines · 109 code · 33 blank · 65 comment · 6 complexity · 1127bfe094cb38b68865695c9f9c99b9 MD5 · raw file

  1. /*
  2. * To change this template, choose Tools | Templates
  3. * and open the template in the editor.
  4. */
  5. package org.ala.rest;
  6. import com.vividsolutions.jts.geom.Point;
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.io.Serializable;
  10. import java.util.ArrayList;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.concurrent.CountDownLatch;
  15. import java.util.concurrent.TimeUnit;
  16. import java.util.logging.Level;
  17. import java.util.logging.Logger;
  18. import javax.servlet.ServletContext;
  19. import org.geoserver.catalog.Catalog;
  20. import org.geoserver.catalog.LayerInfo;
  21. import org.geoserver.config.GeoServer;
  22. import org.geoserver.platform.GeoServerExtensions;
  23. import org.geotools.data.DataStore;
  24. import org.geotools.data.DefaultTransaction;
  25. import org.geotools.data.FeatureSource;
  26. import org.geotools.data.FeatureStore;
  27. import org.geotools.data.Transaction;
  28. import org.geotools.data.shapefile.ShapefileDataStore;
  29. import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  30. import org.geotools.feature.FeatureCollection;
  31. import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
  32. import org.geotools.referencing.crs.DefaultGeographicCRS;
  33. import org.geotools.util.logging.Logging;
  34. import org.opengis.feature.simple.SimpleFeatureType;
  35. import org.vfny.geoserver.util.DataStoreUtils;
  36. /**
  37. *
  38. * @author angus
  39. */
  40. public class Intersector {
  41. GazetteerConfig gc = new GazetteerConfig();
  42. GeoServer gs = GeoServerExtensions.bean(GeoServer.class);
  43. ServletContext sc = GeoServerExtensions.bean(ServletContext.class);
  44. Catalog catalog = gs.getCatalog();
  45. private static final Logger logger = Logging.getLogger("org.ala.rest.GazetteerFeature");
  46. private List<FeatureSource> featureSources = new ArrayList();
  47. private List<String> layers;
  48. private List<String> shapeFiles = new ArrayList();
  49. public Intersector(List<String> layers) {
  50. this.layers = layers;
  51. //Load all the layers to intersect with?
  52. //
  53. // try {
  54. // for (String layerName : layers) {
  55. // if (!gc.layerNameExists(layerName)) {
  56. // logger.log(Level.FINER, "layer {0} does not exist - trying aliases.", layerName);
  57. // layerName = gc.getNameFromAlias(layerName);
  58. // if (layerName.compareTo("") == 0) {
  59. // logger.finer("no aliases found for layer, giving up");
  60. // }
  61. // }
  62. // ///else {
  63. // LayerInfo layerInfo = catalog.getLayerByName(layerName);
  64. // Map params = layerInfo.getResource().getStore().getConnectionParameters();
  65. //
  66. // DataStore dataStore = DataStoreUtils.acquireDataStore(params, sc);
  67. //
  68. // FeatureSource layer = dataStore.getFeatureSource(layerName);
  69. // String shapeFileName = createShapeFile(layerName + ".shp",layer);
  70. // System.out.println("Loading layer: " + layer.getName());
  71. // featureSources.add(layer);
  72. // shapeFiles.add(shapeFileName);
  73. // //}
  74. //
  75. // }
  76. // } catch (IOException e1) {
  77. // logger.log(Level.SEVERE, "IOException in Intersector: {0}", e1.getMessage());
  78. // } catch (Exception e2) {
  79. // logger.log(Level.SEVERE, "Exception while creating shapefile {0}", e2.getMessage());
  80. // }
  81. }
  82. // public List<String[]> intersect(double[][] points) {
  83. // long [] timing = new long[6];
  84. // timing[0] = System.currentTimeMillis();
  85. //
  86. // List<String[]> allResults = new ArrayList();
  87. // //TODO configurable thread count?
  88. // int threadCount = 6;
  89. //
  90. // for(String shapeFileName : shapeFiles) {
  91. // SimpleShapeFile ssf = new SimpleShapeFile(shapeFileName, threadCount);
  92. // String [] results = ssf.intersect(points);
  93. //
  94. // allResults.add(results);
  95. // }
  96. // return allResults;
  97. // }
  98. public List<String[]> intersect(List<Point> points) {
  99. List<String[]> resultSet = new ArrayList();
  100. //Check each point against each region in
  101. System.out.println("Intersecting points ...");
  102. int threadCount = 1;
  103. int step = points.size()/threadCount;
  104. if (step == 0) {
  105. step = 1;
  106. threadCount = points.size();
  107. }
  108. CountDownLatch latch = new CountDownLatch(threadCount);
  109. List<IntersectThread> threads = new ArrayList();
  110. for (int i =0; i < threadCount; i++) {
  111. String[] results = new String[step];
  112. IntersectThread it = new IntersectThread(points.subList(i*step, ((i+1)*step)),layers, results, latch);
  113. threads.add(it);
  114. it.start();
  115. }
  116. try {
  117. latch.await();
  118. } catch (InterruptedException E) {
  119. }
  120. for(IntersectThread it : threads) {
  121. resultSet.add(it.results);
  122. }
  123. return resultSet;
  124. }
  125. private String createShapeFile(String fileName, FeatureSource layer) throws IOException, Exception {
  126. FeatureCollection featureCollection = layer.getFeatures();
  127. File shapeFile = new File(fileName);
  128. ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
  129. Map<String, Serializable> params = new HashMap<String, Serializable>();
  130. params.put("url", shapeFile.toURI().toURL());
  131. params.put("create spatial index", Boolean.TRUE);
  132. ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
  133. newDataStore.createSchema((SimpleFeatureType)layer.getSchema());
  134. /*
  135. * You can comment out this line if you are using the createFeatureType
  136. * method (at end of class file) rather than DataUtilities.createType
  137. */
  138. newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
  139. /*
  140. * Write the features to the shapefile
  141. */
  142. Transaction transaction = new DefaultTransaction("create");
  143. String typeName = newDataStore.getTypeNames()[0];
  144. FeatureSource shapeSource = newDataStore.getFeatureSource(typeName);
  145. if (shapeSource instanceof FeatureStore) {
  146. FeatureStore shapeStore = (FeatureStore) shapeSource;
  147. shapeStore.setTransaction(transaction);
  148. try {
  149. shapeStore.addFeatures(featureCollection);
  150. transaction.commit();
  151. } catch (Exception e) {
  152. logger.severe("Problem writing shapefile: " + e.getMessage());
  153. transaction.rollback();
  154. } finally {
  155. transaction.close();
  156. }
  157. //System.exit(0); // success!
  158. } else {
  159. throw new Exception(typeName + " does not support read/write access");
  160. }
  161. return shapeFile.getAbsolutePath().replace(".shp", "");
  162. }
  163. private static SimpleFeatureType createFeatureType() {
  164. SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
  165. builder.setName("Location");
  166. builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
  167. // add attributes in order
  168. builder.add("Location", Point.class);
  169. builder.length(15).add("Name", String.class); // <- 15 chars width for name field
  170. // build the type
  171. final SimpleFeatureType LOCATION = builder.buildFeatureType();
  172. return LOCATION;
  173. }
  174. }