Project

General

Profile

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

    
25
import java.io.File;
26

    
27
import edu.ucsb.nceas.metacat.database.DBConnection;
28
import edu.ucsb.nceas.metacat.properties.PropertyService;
29
import edu.ucsb.nceas.metacat.util.MetacatUtil;
30
import edu.ucsb.nceas.metacat.util.SystemUtil;
31
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
32

    
33
import com.vividsolutions.jts.geom.Coordinate;
34
import com.vividsolutions.jts.geom.Point;
35
import com.vividsolutions.jts.geom.Polygon;
36
import com.vividsolutions.jts.geom.MultiPolygon;
37
import com.vividsolutions.jts.geom.MultiPoint;
38
import com.vividsolutions.jts.geom.GeometryFactory;
39
import com.vividsolutions.jts.geom.PrecisionModel;
40

    
41
import org.geotools.feature.AttributeType;
42
import org.geotools.feature.AttributeTypeFactory;
43
import org.geotools.feature.Feature;
44
import org.geotools.feature.FeatureType;
45
import org.geotools.feature.FeatureTypeFactory;
46
import org.geotools.feature.SchemaException;
47

    
48
import java.sql.ResultSet;
49
import java.sql.PreparedStatement;
50
import java.util.Vector;
51

    
52
import org.apache.log4j.Logger;
53

    
54
/**
55
 * 
56
 * Class representing the spatial portions of an xml document as a geotools
57
 * Feature.
58
 */
59
public class SpatialDocument {
60

    
61
	private DBConnection dbconn;
62

    
63
	private static Logger log = Logger.getLogger(SpatialDocument.class.getName());
64

    
65
	private SpatialFeatureSchema featureSchema = new SpatialFeatureSchema();
66

    
67
	Vector west = new Vector();
68
	Vector south = new Vector();
69
	Vector east = new Vector();
70
	Vector north = new Vector();
71

    
72
	String title = "";
73
	String docid = null;
74

    
75
	/**
76
	 * Constructor that queries the db
77
	 * 
78
	 * @param docid
79
	 *            The document id to be represented spatially
80
	 * @param dbconn
81
	 *            The database connection shared from the refering method.
82
	 */
83
	public SpatialDocument(String docid, DBConnection dbconn) {
84

    
85
		this.docid = docid;
86
		PreparedStatement pstmt = null;
87
		ResultSet rs = null;
88
		this.dbconn = dbconn;
89
		boolean isSpatialDocument = false;
90
		String thisDocname = null;
91
		String westPath = null;
92
		String eastPath = null;
93
		String northPath = null;
94
		String southPath = null;
95

    
96
		/*
97
		 * Determine the docname/schema and decide how to proceed with spatial
98
		 * harvest
99
		 */
100
		String query = "SELECT docname FROM xml_documents WHERE docid='" + docid.trim()
101
				+ "';";
102
		String docname = "";
103
		try {
104
			pstmt = dbconn.prepareStatement(query);
105
			pstmt.execute();
106
			rs = pstmt.getResultSet();
107
			while (rs.next()) {
108
				docname = rs.getString(1);
109
			}
110
			rs.close();
111
			pstmt.close();
112
		} catch (Exception e) {
113
			log.error(" ---- Could not get docname for " + docid);
114
			e.printStackTrace();
115
		}
116
		if (docname == null)
117
			docname = "";
118

    
119
		// Loop through all our spatial docnames and determine if the current
120
		// document matches
121
		// If so, get the appropriate corner xpaths
122
		try {
123
			Vector spatialDocnames = MetacatUtil.getOptionList(PropertyService
124
					.getProperty("spatial.spatialDocnameList"));
125
			for (int i = 0; i < spatialDocnames.size(); i++) {
126
				thisDocname = ((String) spatialDocnames.elementAt(i)).trim();
127
				if (docname.trim().equals(thisDocname)) {
128
					isSpatialDocument = true;
129

    
130
					// determine its east,west,north and south coord xpaths
131
					westPath = PropertyService.getProperty("spatial." + thisDocname
132
							+ "_westBoundingCoordinatePath");
133
					eastPath = PropertyService.getProperty("spatial." + thisDocname
134
							+ "_eastBoundingCoordinatePath");
135
					northPath = PropertyService.getProperty("spatial." + thisDocname
136
							+ "_northBoundingCoordinatePath");
137
					southPath = PropertyService.getProperty("spatial." + thisDocname
138
							+ "_southBoundingCoordinatePath");
139
				}
140
			}
141
		} catch (PropertyNotFoundException pnfe) {
142
			log.error("Could not find spatialDocnameList or bounding coordinate "
143
					+ "path for: " + docid);
144
			pnfe.printStackTrace();
145
		}
146

    
147
		// If it is a spatial document, harvest the corners and title
148
		if (isSpatialDocument) {
149

    
150
			/*
151
			 * Get the bounding coordinates
152
			 */
153
			query = "SELECT path, nodedatanumerical, parentnodeid FROM xml_path_index"
154
					+ " WHERE docid = '"
155
					+ docid.trim()
156
					+ "'"
157
					+ " AND docid IN (SELECT distinct docid FROM xml_access WHERE docid = '"
158
					+ docid.trim()
159
					+ "' AND principal_name = 'public' AND perm_type = 'allow')"
160
					+ " AND (path = '" + westPath + "'" + "  OR path = '" + southPath
161
					+ "'" + "  OR path = '" + eastPath + "'" + "  OR path = '"
162
					+ northPath + "'" + " ) ORDER BY parentnodeid;";
163

    
164
			try {
165
				pstmt = dbconn.prepareStatement(query);
166
				pstmt.execute();
167
				rs = pstmt.getResultSet();
168
				while (rs.next()) {
169
					if (rs.getString(1).equals(westPath))
170
						this.west.add(new Float(rs.getFloat(2)));
171
					else if (rs.getString(1).equals(southPath))
172
						this.south.add(new Float(rs.getFloat(2)));
173
					else if (rs.getString(1).equals(eastPath))
174
						this.east.add(new Float(rs.getFloat(2)));
175
					else if (rs.getString(1).equals(northPath))
176
						this.north.add(new Float(rs.getFloat(2)));
177
					else
178
						log.error("** An xml path not related to your bounding coordinates was returned by this query \n"
179
										+ query + "\n");
180
				}
181
				rs.close();
182
				pstmt.close();
183
			} catch (Exception e) {
184
				log.error(" ---- Could not get bounding coordinates for " + docid);
185
				e.printStackTrace();
186
			}
187

    
188
			/*
189
			 * Get the title
190
			 */
191

    
192
			try {
193

    
194
				String docTitlePath = PropertyService.getProperty("spatial.docTitle");
195
				query = "select nodedata from xml_path_index where path = '"
196
						+ docTitlePath.trim() + "' and docid = '" + docid.trim() + "'";
197
				pstmt = dbconn.prepareStatement(query);
198
				pstmt.execute();
199
				rs = pstmt.getResultSet();
200
				if (rs.next())
201
					this.title = rs.getString(1);
202
				rs.close();
203
				pstmt.close();
204
			} catch (Exception e) {
205
				log.error(" **** Error getting docids from getTitle for docid = "
206
								+ docid);
207
				e.printStackTrace();
208
				this.title = docid;
209
			}
210
		}
211

    
212
  }
213

    
214
  /**
215
	 * Returns a geotools (multi)polygon feature with geometry plus attributes
216
	 * ready to be inserted into our spatial dataset cache
217
	 */
218
  public Feature getPolygonFeature() {
219
      // Get polygon feature type
220
      FeatureType polyType = featureSchema.getPolygonFeatureType();
221

    
222
      MultiPolygon theGeom = getPolygonGeometry();
223
      if (theGeom == null)
224
          return null;
225

    
226
      // Populate the feature schema
227
      try {
228
          Feature polyFeature = polyType.create(new Object[]{ 
229
              theGeom,
230
              this.docid,
231
              getUrl(this.docid), 
232
              this.title });
233
          return polyFeature; 
234
      } catch (org.geotools.feature.IllegalAttributeException e) {
235
          log.error("!!!!!!! org.geotools.feature.IllegalAttributeException");
236
          return null;
237
      }
238
  }
239

    
240
  /**
241
   * Returns a geotools (multi)point feature with geometry plus attributes
242
   * ready to be inserted into our spatial dataset cache
243
   *
244
   */
245
  public Feature getPointFeature() {
246
      // Get polygon feature type
247
      FeatureType pointType = featureSchema.getPointFeatureType();
248

    
249
      MultiPoint theGeom = getPointGeometry();
250
      if (theGeom == null)
251
          return null;
252

    
253
      // Populate the feature schema
254
      try {
255
          Feature pointFeature = pointType.create(new Object[]{ 
256
              theGeom,
257
              this.docid,
258
              getUrl(this.docid), 
259
              this.title });
260
          return pointFeature;
261
      } catch (org.geotools.feature.IllegalAttributeException e) {
262
          log.error("!!!!!!! org.geotools.feature.IllegalAttributeException");
263
          return null;
264
      }
265
  }
266

    
267
  /**
268
   * Given a valid docid, return an appropriate URL
269
   * for viewing the metadata document
270
   *
271
   * @param docid The document id for which to construct the access url.
272
   */
273
  private String getUrl( String docid ) {
274
     String docUrl = null;
275
     try {
276
    	 docUrl = SystemUtil.getServletURL()
277
                    + "?action=read&docid=" + docid 
278
                    + "&qformat=" 
279
                    + PropertyService.getProperty("application.default-style");
280
     } catch (PropertyNotFoundException pnfe) {
281
    	 log.error("Could not get access url because of unavailable property: " 
282
    			 + pnfe.getMessage());
283
     }
284

    
285
     return docUrl;
286
  }
287

    
288

    
289
  /**
290
   * Returns a mutlipolygon geometry representing the geographic coverage(s) of the document
291
   *
292
   */
293
  private MultiPolygon getPolygonGeometry() {
294

    
295
    PrecisionModel precModel = new PrecisionModel(); // default: Floating point
296
    GeometryFactory geomFac = new GeometryFactory( precModel, featureSchema.srid );
297
    Vector polygons = new Vector();
298
    float w;
299
    float s;
300
    float e;
301
    float n;
302

    
303
    if ( west.size() == south.size() && south.size() == east.size() && east.size() == north.size() ) {
304
        for (int i = 0; i < west.size(); i++) {
305

    
306
            w = ((Float)west.elementAt(i)).floatValue();
307
            s = ((Float)south.elementAt(i)).floatValue();
308
            e = ((Float)east.elementAt(i)).floatValue();
309
            n = ((Float)north.elementAt(i)).floatValue();
310

    
311
            // Check if it's actually a valid polygon
312
            if (  w == 0.0 && s == 0.0 && e == 0.0 && n == 0.0) {
313
                log.warn("        Invalid or empty coodinates ... skipping");
314
                continue;
315
            } else if( Float.compare(w, e) == 0 && Float.compare(n,s) == 0 ) {
316
                log.warn("        Point coordinates only.. skipping polygon generation");
317
                continue;
318
            }
319

    
320
            // Handle the case of crossing the dateline and poles
321
            // dateline crossing is valid 
322
            // polar crossing is not ( so we swap north and south )
323
            // Assumes all coordinates are confined to -180 -90 180 90
324
            float dl = 180.0f;
325
            float _dl = -180.0f;
326
            
327
            if ( w > e && s > n ) {
328
                log.info( "Crosses both the dateline and the poles .. split into 2 polygons, swap n & s" );
329
                polygons.add( createPolygonFromBbox( geomFac,   w,   n, dl, s ) );
330
                polygons.add( createPolygonFromBbox( geomFac, _dl,   n,  e, s ) );
331
            } else if ( w > e ) {
332
                log.info( "Crosses the dateline .. split into 2 polygons" );
333
                polygons.add( createPolygonFromBbox( geomFac,   w, s, dl, n ) );
334
                polygons.add( createPolygonFromBbox( geomFac, _dl, s,  e, n ) );
335
            } else if ( s > n ) {
336
                log.info( "Crosses the poles .. swap north and south" );
337
                polygons.add( createPolygonFromBbox( geomFac, w, n, e, s ) );
338
            } else {
339
                // Just a standard polygon that fits nicely onto our flat earth
340
                polygons.add( createPolygonFromBbox( geomFac, w, s, e, n ) );    
341
            }
342

    
343
             
344
        }
345
    } else {
346
       log.error(" *** Something went wrong.. your east,west,north and south bounding arrays are different sizes!");
347
    }
348
    
349
    if( polygons.size() > 0 ) {
350
       Polygon[] polyArray = geomFac.toPolygonArray( polygons );
351
       MultiPolygon multiPolyGeom= geomFac.createMultiPolygon( polyArray );
352
       return multiPolyGeom; 
353
    } else {
354
       return null;
355
    } 
356

    
357
  }
358
   
359

    
360
  /**
361
   * Returns a polygon given the four bounding box coordinates
362
   */
363
  private Polygon createPolygonFromBbox( GeometryFactory geomFac, float w, float s, float e, float n ) {
364

    
365
        Coordinate[] linestringCoordinates = new Coordinate[5];
366

    
367
        linestringCoordinates[0] = new Coordinate( w, s );
368
        linestringCoordinates[1] = new Coordinate( w, n );
369
        linestringCoordinates[2] = new Coordinate( e, n );
370
        linestringCoordinates[3] = new Coordinate( e, s );
371
        linestringCoordinates[4] = new Coordinate( w, s );
372

    
373
        return geomFac.createPolygon( geomFac.createLinearRing(linestringCoordinates), null);
374
  }
375

    
376

    
377
  /**
378
   * Returns a multipoint geometry represnting the geographic coverage(s) of the document
379
   *
380
   * @todo Handle the case of crossing the dateline and poles
381
   */
382
  private MultiPoint getPointGeometry() {
383

    
384
    PrecisionModel precModel = new PrecisionModel(); // default: Floating point
385
    GeometryFactory geomFac = new GeometryFactory( precModel, featureSchema.srid );
386
    float w;
387
    float s;
388
    float e;
389
    float n;
390

    
391
    PreparedStatement pstmt = null;
392
    ResultSet rs = null;
393

    
394
    Vector points = new Vector();
395

    
396
    if ( west.size() == south.size() && south.size() == east.size() && east.size() == north.size() ) {
397
        for (int i = 0; i < west.size(); i++) {
398

    
399
            w = ((Float)west.elementAt(i)).floatValue();
400
            s = ((Float)south.elementAt(i)).floatValue();
401
            e = ((Float)east.elementAt(i)).floatValue();
402
            n = ((Float)north.elementAt(i)).floatValue();
403

    
404
            // Check if it's actually a valid point
405
            if (  w == 0.0f && s == 0.0f && e == 0.0f && n == 0.0f) {
406
                 log.warn("        Invalid or empty coodinates ... skipping");
407
                 continue;
408
            }
409

    
410
            float xCenter;
411
            float yCenter;
412

    
413
            // Handle the case of crossing the dateline and poles
414
            // Assumes all coordinates are confined to -180 -90 180 90
415

    
416
            if ( w > e ) {
417
                log.info( "Crosses the dateline .. " );
418
                xCenter = (360.0f - w + e)/ 2.0f + w;
419
                if( xCenter > 180.0f )
420
                    xCenter = xCenter - 360.0f;
421
                yCenter = ( s + n ) / 2.0f;
422
            } else {
423
                // Just a standard point that can be calculated by the average coordinates
424
                xCenter = ( w + e ) / 2.0f;
425
                yCenter = ( s + n ) / 2.0f;
426
            }
427

    
428
            points.add( geomFac.createPoint( new Coordinate( xCenter, yCenter)) );
429
        }
430
    } else {
431
       log.error(" *** Something went wrong.. your east,west,north and south bounding vectors are different sizes!");
432
    }
433
    
434
    if( points.size() > 0 ) {
435
       Point[] pointArray = geomFac.toPointArray( points );
436
       MultiPoint multiPointGeom= geomFac.createMultiPoint( pointArray );
437
       return multiPointGeom; 
438
    } else {
439
       return null;
440
    } 
441

    
442

    
443
  }
444
}
(3-3/8)