Project

General

Profile

« Previous | Next » 

Revision 3044

Added by perry about 18 years ago

Rewrote spatial query handler to use geotools directly against the spatial cache.

View differences:

src/edu/ucsb/nceas/metacat/spatial/SpatialQuery.java
1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *             National Center for Ecological Analysis and Synthesis
5
 *
6
 * Author: Matthew Perry 
7
 * '$Date$'
8
 * '$Revision$'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24

  
25
package edu.ucsb.nceas.metacat.spatial;
26

  
27
import org.geotools.feature.FeatureType;
28
import org.geotools.data.shapefile.ShapefileDataStore;
29
import org.geotools.data.FeatureStore;
30
import org.geotools.data.FeatureSource;
31
import org.geotools.data.DefaultTransaction;
32
import org.geotools.data.Transaction;
33
import org.geotools.feature.Feature;
34
import org.geotools.filter.Filter;
35
import org.geotools.filter.AbstractFilter;
36
import org.geotools.filter.Expression;
37
import org.geotools.filter.CompareFilter;
38
import org.geotools.filter.GeometryFilter;
39
import org.geotools.filter.FilterFactory;
40
import org.geotools.filter.FilterFactoryFinder;
41
import org.geotools.filter.IllegalFilterException;
42
import org.geotools.feature.FeatureCollection;
43
import org.geotools.feature.FeatureCollections;
44
import com.vividsolutions.jts.geom.Envelope;
45

  
46
import java.io.File;
47
import java.net.URI;
48
import java.net.URL;
49
import java.net.MalformedURLException;
50
import java.sql.ResultSet;
51
import java.sql.PreparedStatement;
52
import java.util.Vector;
53
import java.util.Iterator; 
54
import java.io.IOException;
55

  
56
import org.apache.log4j.Logger;
57

  
58
import edu.ucsb.nceas.metacat.MetaCatUtil;
59

  
60
/** 
61
 * Class to query the persistent spatial cache
62
 * and returns docids matching spatial constraints
63
 */
64
public class SpatialQuery {
65
 
66
  private static Logger log = Logger.getLogger(SpatialQuery.class.getName());
67
 
68
  /** 
69
   * empty constructor to initialize spatial query
70
   */
71
  public SpatialQuery() { }
72
 
73
  /**
74
   * Querys all features in the spatial cache 
75
   * and filters based on bouding coordinates.
76
   * Returns Vector of docids.
77
   *
78
   * @param w West bounding coordinate 
79
   * @param s South bounding coordinate 
80
   * @param e East bounding coordinate 
81
   * @param n North bounding coordinate 
82
   *
83
   */
84
  public Vector filterByBbox( Float w, Float s, Float e, Float n ) {
85
      Vector docids = new Vector();
86
      SpatialFeatureSchema featureSchema = new SpatialFeatureSchema();
87
      
88
      // MPTDO, perform geotools spatial query
89
      // test
90
      docids.add("test1.1");
91
      docids.add("test2.1");
92

  
93
      ShapefileDataStore store = null;
94
      FeatureSource features = null;
95
      FeatureCollection collection = null;
96
      FilterFactory filterFactory = FilterFactoryFinder.createFilterFactory();
97

  
98
      try {
99
          store = new ShapefileDataStore( (new File( featureSchema.polygonShpUri )).toURL() );
100
          features = store.getFeatureSource(store.getTypeNames()[0]);
101
          //count features
102
          //col = features.getFeatures();
103
          //System.out.println("# cities (no filter)= "+col.size());
104

  
105
          Envelope envelope = new Envelope( w, e, s, n ); 
106
          Expression bbox = filterFactory.createBBoxExpression( envelope );
107

  
108
          FeatureType featureType = store.getSchema( store.getTypeNames()[0] );
109
          Expression geometry = filterFactory.createAttributeExpression( featureType.getDefaultGeometry().getName()  );
110
          GeometryFilter bboxFilter = filterFactory.createGeometryFilter(AbstractFilter.GEOMETRY_BBOX);
111
          bboxFilter.addLeftGeometry( geometry );
112
          bboxFilter.addRightGeometry( bbox );
113

  
114
          //count filtered features
115
          collection = features.getFeatures(bboxFilter);
116
          //System.out.println("# cities (after filter)= "+col.size());
117

  
118
          Iterator iterator = collection.iterator();
119
          try {
120
              for( Iterator i=collection.iterator(); i.hasNext(); ) {
121
                  Feature feature = (Feature) i.next();
122
                  docids.add( (String) feature.getAttribute(1) );
123
              }
124
          } finally {
125
              collection.close( iterator );
126
          }
127
         
128
        } catch (MalformedURLException ex) {
129
            ex.printStackTrace();
130
        } catch (IOException ex) {
131
            ex.printStackTrace();
132
        } catch (IllegalFilterException ex) {
133
            ex.printStackTrace();
134
        }
135

  
136

  
137
      return docids;
138

  
139
  }
140

  
141
}
0 142

  
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
71 71

  
72 72
import edu.ucsb.nceas.utilities.Options;
73 73
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
74
import edu.ucsb.nceas.metacat.spatial.SpatialQuery;
74 75

  
75 76
/**
76 77
 * A metadata catalog server implemented as a Java Servlet
......
787 788
                                    String username, String[] groupnames, 
788 789
                                    String sess_id) {
789 790
      
790
      Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
791
        Logger logMetacat = Logger.getLogger(MetaCatServlet.class);
791 792

  
792 793
	if ( !MetaCatUtil.getOption("runSpatialOption").equals("true") ) {
793 794
        	response.setContentType("text/html");
......
796 797
		return ;
797 798
	}		
798 799
      
799
      //MetacatSpatialQuery _spatialQuery = new MetacatSpatialQuery();
800
      
801
      
802
      // switch -- html/xml print
803
      //MBJDELETED boolean printXML = false; 
804
      
805
      // get the spatial parameters
806
      logMetacat.debug("params: " +  params);
807
      //String _xmax =  (String)params.get("XMAX");
808
      float _xmax = Float.parseFloat( ((String[]) params.get("XMAX"))[0] );
809
      float _ymax = Float.parseFloat( ((String[]) params.get("YMAX"))[0] );
810
      float _xmin = Float.parseFloat( ((String[]) params.get("XMIN"))[0] );
811
      float _ymin = Float.parseFloat( ((String[]) params.get("YMIN"))[0] );
812
      logMetacat.debug("\nxmax: " + _xmax + " \nymax:" + _ymax +
813
                      "\nxmin: " + _xmin + "\nymin: " + _ymin);
800
        /* 
801
         * Perform spatial query against spatial cache
802
         */
803
        Float _xmax = Float.parseFloat( ((String[]) params.get("XMAX"))[0] );
804
        Float _ymax = Float.parseFloat( ((String[]) params.get("YMAX"))[0] );
805
        Float _xmin = Float.parseFloat( ((String[]) params.get("XMIN"))[0] );
806
        Float _ymin = Float.parseFloat( ((String[]) params.get("YMIN"))[0] );
814 807

  
815
      // create an s-query
816
      String spatialQuery = createSpatialQuery(_xmin, _ymin, _xmax, _ymax);
817
      String[] queryArray = new String[1];
818
      queryArray[0] = spatialQuery;
819
      params.put("query", queryArray);
808
        SpatialQuery sq = new SpatialQuery();
809
        Vector docids = sq.filterByBbox( _xmin, _ymin, _xmax, _ymax );
810
        logMetacat.info(" --- Spatial Query completed. Passing on the SQuery handler");
820 811

  
821
      // qformat
822
      String[] qformatArray = new String[1];
823
      try {
824
          String _skin = ((String[]) params.get("SKIN"))[0];
825
          qformatArray[0] = _skin;
826
      } catch (java.lang.NullPointerException e) {
827
          // should be "default" but keep this for backwards compatibility with knp site
828
          logMetacat.warn("No SKIN specified for metacat actions=spatial_query... defaulting to 'knp' skin !\n");
829
          qformatArray[0] = "knp";
830
      }
831
      params.put("qformat", qformatArray);
812
        /*
813
         * Create an squery based on vector of matching docids
814
         */
815
        String [] docidArray = new String[docids.size()];
816
        docids.toArray(docidArray);
817
        String squery = DocumentIdQuery.createDocidQuery( docidArray );
832 818

  
833
      // change the action
834
      String[] actionArray = new String[1];
835
      actionArray[0] = "squery";
836
      params.put("action", actionArray);
819
        /*
820
         * Pass to squery handler
821
         */
822
        String[] queryArray = new String[1];
823
        queryArray[0] = squery;
824
        params.put("query", queryArray);
837 825

  
838
      handleSQuery(out, params, response, username, groupnames, sess_id);
826
        // qformat
827
        String[] qformatArray = new String[1];
828
        try {
829
            String _skin = ((String[]) params.get("SKIN"))[0];
830
            qformatArray[0] = _skin;
831
        } catch (java.lang.NullPointerException e) {
832
            // should be "default" but keep this for backwards compatibility with knp site
833
            logMetacat.warn("No SKIN specified for metacat actions=spatial_query... defaulting to 'knp' skin !\n");
834
            qformatArray[0] = "knp";
835
        }
836
        params.put("qformat", qformatArray);
839 837

  
838
        // change the action
839
        String[] actionArray = new String[1];
840
        actionArray[0] = "squery";
841
        params.put("action", actionArray);
840 842

  
841
/* MBJ DELETED -- using Metacat query instead
842
      // issue the Spatial query 
843
      //MBJ DELETED MetacatSpatialDataset _data =  
844
        //MBJ DELETED _spatialQuery.queryDatasetByCartesianBounds(_xmin, _ymin, _xmax, _ymax);
843
        handleSQuery(out, params, response, username, groupnames, sess_id);
845 844

  
846
      // report the number of documents returned:
847
      //MBJ DELETED logMetacat.warn("\nThe number of documents in the BBOX query: " 
848
              //MBJ DELETED + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
849
     
850
if (  _data.size() > 0) { 
851
      logMetacat.warn("\nThe number of documents in the BBOX query: " 
852
              + _data.size()+" the doc. list: '" + _data.toTXT().trim()+"'" );
853
     
854
      
855
      // create an s-query
856
      String[] queryArray = new String[1];
857
      queryArray[0] = DocumentIdQuery.createDocidQuery(_data.getDocidList());
858
      params.put("query", queryArray);
859
      
860
      // qformat        
861
      String[] qformatArray = new String[1];
862
      qformatArray[0] = "knp";
863
      params.put("qformat", qformatArray);
845
  }
864 846

  
865
      // change the action 
866
      String[] actionArray = new String[1];
867
      actionArray[0] = "squery";
868
      params.put("action", actionArray);
869

  
870
      // return the list of docs and point at the spatial theme 
871
      if ( printXML) {
872
        response.setContentType("text/xml");
873
        out.println(_data.toXML() ); // write the data as xml
874
        out.close();
875
      } else {
876
        logMetacat.warn("username: " + username+"\nsession: "+sess_id);
877
        handleSQuery(out, params, response, username, groupnames, sess_id);  
878
      }
879
} else {
880
        response.setContentType("text/html");
881
        out.println("<html>No Datasets Selected <html>");
882
        out.close();
883
}
884
*/
885

  
886
    }
887

  
888 847
    /**
889 848
     * Create a metacat squery for spatial data coordinates.
890 849
     */

Also available in: Unified diff