PageRenderTime 51ms CodeModel.GetById 10ms app.highlight 35ms RepoModel.GetById 2ms app.codeStats 0ms

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

http://alageospatialportal.googlecode.com/
Java | 210 lines | 145 code | 42 blank | 23 comment | 23 complexity | 40fa32590716d4182f1ee21034d5f467 MD5 | raw file
  1package org.ala.rest;
  2
  3import com.vividsolutions.jts.geom.Geometry;
  4import java.io.IOException;
  5import java.io.StringWriter;
  6import java.text.DecimalFormat;
  7import java.util.ArrayList;
  8import java.util.Collection;
  9import java.util.HashMap;
 10import java.util.List;
 11import org.geotools.data.DataStore;
 12
 13import java.util.Map;
 14import java.util.logging.Logger;
 15
 16import javax.servlet.ServletContext;
 17
 18import org.geoserver.catalog.Catalog;
 19import org.geoserver.catalog.LayerInfo;
 20import org.geotools.data.FeatureSource;
 21import org.geotools.feature.FeatureIterator;
 22import org.opengis.feature.Feature;
 23
 24import org.geoserver.config.GeoServer;
 25
 26import org.geoserver.platform.GeoServerExtensions;
 27import org.geotools.filter.text.cql2.CQL;
 28import org.opengis.feature.Property;
 29
 30
 31import org.vfny.geoserver.util.DataStoreUtils;
 32import org.geoserver.wfs.response.GeoJSONBuilder;
 33import org.geotools.util.logging.Logging;
 34import org.opengis.feature.type.GeometryType;
 35import org.opengis.geometry.BoundingBox;
 36
 37/**
 38 *
 39 *@author angus
 40 */
 41public class GazetteerFeature {
 42
 43    private static final Logger logger = Logging.getLogger("org.ala.rest.GazetteerFeature");
 44    String id;
 45    String name;
 46    Map advanced_properties; //detailed feature metadata
 47    Map<String,String> properties;    //basic feature metadata (to displayed in UI)
 48    List<String> geometries = new ArrayList<String>();
 49
 50    /**
 51     * Instantiates a gazetteer feature given an id string and layer name
 52     * @param layerName
 53     * @param idAttribute1
 54     * @throws IOException
 55     * @throws Exception
 56     */
 57    public GazetteerFeature(String layerName, String idAttribute1) throws IOException, Exception {
 58
 59        logger.finer("param: layerName: " + layerName);
 60        logger.finer("param: idAttribute1: " + idAttribute1);
 61
 62        GazetteerConfig gc = new GazetteerConfig();
 63
 64        GeoServer gs = GeoServerExtensions.bean(GeoServer.class);
 65        ServletContext sc = GeoServerExtensions.bean(ServletContext.class);
 66        Catalog catalog = gs.getCatalog();
 67
 68        //check to see if layer exists, if not check to see if alias exists ...
 69        if (!gc.layerNameExists(layerName)) {
 70            logger.finer("layer " + layerName + " does not exist - trying aliases.");
 71            layerName = gc.getNameFromAlias(layerName);
 72            if (layerName.compareTo("") == 0) {
 73                logger.finer("no aliases found for layer, giving up");
 74                return;
 75            }
 76        }
 77
 78        //Use search to find matches (provides case insensitive matching)
 79        String[] layers = {layerName};
 80        String searchTerms = idAttribute1;
 81
 82        Search search = new Search(searchTerms, layers, "id");
 83        ArrayList<SearchResultItem> results = search.getResults();
 84        if (results.size() == 0) {
 85            logger.severe("No results returned - this isn't great");
 86            throw new Exception("No results returned - this isn't great");
 87        }
 88        logger.finer("Number of hits is " + results.size());
 89
 90        SearchResultItem searchResultItem = results.get(0);
 91
 92        //grab the first result (highest hit)
 93        logger.finer("Match idAttribute1: " + searchResultItem.idAttribute1);
 94
 95        idAttribute1 = searchResultItem.idAttribute1;
 96
 97        LayerInfo layerInfo = catalog.getLayerByName(layerName);
 98        Map params = layerInfo.getResource().getStore().getConnectionParameters();
 99
100        DataStore dataStore = DataStoreUtils.acquireDataStore(params, sc);
101
102        try {
103
104            if (dataStore == null) {
105                throw new Exception("Could not find datastore for this layer");
106
107            } else {
108                FeatureSource layer = dataStore.getFeatureSource(layerName);
109                String cql = gc.getIdAttribute1Name(layerName) + "='" + idAttribute1.replace('_', ' ') + "'";
110                logger.finer("cql: " + cql);
111
112                FeatureIterator features = layer.getFeatures(CQL.toFilter(cql)).features();
113
114                try {
115                    if (features.hasNext()) {
116                        while (features.hasNext()) {
117                            Feature feature = (Feature) features.next();
118                            String layerAlias = "";
119                            layerAlias = gc.getLayerAlias(layerName);
120                            if (layerAlias.compareTo("") == 0){
121                                layerAlias = layerName;
122                            }
123                            logger.finer("Layer Alias is : " + layerAlias);
124
125                            this.id = layerAlias + "/" + feature.getProperty(gc.getIdAttribute1Name(layerName)).getValue().toString().replace(" ", "_");
126                            logger.info("Feature ID is : " + this.id);
127
128                            this.properties = new HashMap<String,String>();
129                            this.properties.put("Feature_ID", this.id);
130
131                            this.name = feature.getProperty(gc.getNameAttributeName(layerName)).getValue().toString();
132                            logger.info("Feature Name is : " + this.name);
133                            this.properties.put("Feature_Name", this.name);
134
135                            //Construct a geoJSON representation of the geometry using GeoJSONBuilder
136                            //logger.info("Feature geom is " + feature.getDefaultGeometryProperty().getValue().toString());
137
138                            StringWriter w = new StringWriter();
139                            GeoJSONBuilder geoJson = new GeoJSONBuilder(w);
140                            geoJson.writeGeom((Geometry) feature.getDefaultGeometryProperty().getValue());
141
142
143                            BoundingBox bb = feature.getBounds();
144
145                            Double minx = new Double(bb.getMinX());
146                            Double miny = new Double(bb.getMinY());
147                            Double maxx = new Double(bb.getMaxX());
148                            Double maxy = new Double(bb.getMaxY());
149
150                            if (maxx.compareTo(minx) == 0 && maxy.compareTo(miny) == 0){
151                                String point = "(" + strRoundDouble(miny) + "," + strRoundDouble(minx) + ")";
152                                this.properties.put("Point", point);
153                                logger.finer("Point is: " + point);
154                            }
155                            else{
156                                String boundingBox = "((" + strRoundDouble(miny) + "," + strRoundDouble(minx) + "),(" + strRoundDouble(maxy) + "," + strRoundDouble(maxx) + "))";
157                                this.properties.put("Bounding_Box", boundingBox);
158                                logger.finer("Bounding box is: " + boundingBox);
159                            }
160			                //Get Metadata link from config
161                            this.properties.put("Layer_Metadata", gc.getMetadataPath(layerName));
162                            logger.finer("Layer metadata url is " + gc.getBaseURL() + "/layers/" + layerName);
163                            this.geometries.add(w.toString());
164
165                            //Add all the feature properties to the geojson properties object
166                            Collection<Property> featureProperties = feature.getProperties();
167                            String geomName = feature.getDefaultGeometryProperty().getName().toString();
168                            this.advanced_properties = new HashMap();
169                            for (Property property : featureProperties) {
170                                if ((property.getName() != null) && (property.getValue() != null) && (!(property.getName().toString().contentEquals(geomName)))) {
171                                    this.properties.put(property.getName().toString(), property.getValue().toString());
172                                }
173                            }
174                        }
175                    } else {
176                        throw new Exception("Could not find feature");
177                    }
178                } finally {
179                    features.close();
180                }
181
182            }
183        } finally {
184            dataStore.dispose();
185
186        }
187    }
188
189    public Map getJSONMap() {
190        Map<String, Object> map = new HashMap<String, Object>();
191        map.put("type", "GeometryCollection");
192        map.put("id", this.id);
193        map.put("name", this.name);
194        map.put("properties", this.properties);
195        map.put("geometries", this.geometries);
196        return map;
197    }
198
199    /**
200     * Returns a string representation of a Double to four decimal places
201     * @param inValue
202     * @return
203     */
204    public String strRoundDouble(Double inValue){
205        DecimalFormat fourDec = new DecimalFormat("0.0000");
206        fourDec.setGroupingUsed(false);
207        return fourDec.format(inValue.doubleValue());
208}
209}
210