Project

General

Profile

« Previous | Next » 

Revision 3040

Added by perry almost 18 years ago

Added javadoc comments for all new spatial classes. Optimized the title query in SpatialDocument.

View differences:

src/edu/ucsb/nceas/metacat/spatial/SpatialQueryProcessor.java
1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2003 Regents of the University of California.
4
 *
5
 * Author: John Harris
6
 * '$Date$'
7
 * '$Revision$'
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
import java.io.FileReader;
27
import java.io.PrintWriter;
28
import java.io.IOException;
29
import java.io.StringReader;
30
import java.io.BufferedReader;
31
import java.io.Reader;
32
import java.io.FileInputStream;
33
import java.io.BufferedInputStream;
34
import java.util.Enumeration;
35
import java.util.Hashtable;
36
import java.util.ResourceBundle;
37
import java.util.Random;
38
import java.util.StringTokenizer;
39
import java.util.Properties;
40
import java.util.PropertyResourceBundle;
41
import java.util.Vector;
42
import java.util.Map;
43

  
44
import edu.ucsb.nceas.metacat.client.Metacat;
45
import edu.ucsb.nceas.metacat.DBConnection;
46
import edu.ucsb.nceas.metacat.client.MetacatFactory;
47
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
48
import edu.ucsb.nceas.metacat.client.MetacatException;
49
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
50
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
51
import edu.ucsb.nceas.utilities.IOUtil;
52

  
53
import java.sql.ResultSet;
54
import java.sql.PreparedStatement;
55

  
56
import org.apache.log4j.Logger;
57
import org.apache.log4j.BasicConfigurator;
58
import org.apache.log4j.PropertyConfigurator;
59

  
60
public class SpatialQueryProcessor {
61

  
62
  private String METACATURL =
63
      "http://nebulous.msi.ucsb.edu:9999/knp/metacat";
64
  private File QUERYFILE = null;
65
  private String MCUSER = "uid=harris,o=NCEAS,dc=ecoinformatics,dc=org";
66
  private String MCPASS = "yeahRight";
67

  
68

  
69

  
70

  
71
  private DBConnection dbconn;
72

  
73
  private static Logger log =
74
      Logger.getLogger(SpatialQueryProcessor.class.getName());
75

  
76
        /** constructor that uses the defaults **/
77
  public SpatialQueryProcessor() {
78
    try {
79
      dbconn = new DBConnection();
80
    } catch(java.sql.SQLException se) {
81
      log.fatal("Error connecting to the database ...");
82
      se.getMessage();
83
    }
84
  }
85

  
86
  /** call this after the processor is done **/
87
  protected void close() {
88
    try {
89
      dbconn.close();
90
    } catch(java.sql.SQLException se) {
91
      log.fatal("Error closing connecting to the database ...");
92
      se.getMessage();
93
    }
94
  }
95

  
96
  public SpatialQueryProcessor(String mcUser, String mcPass,
97
                               String metacatUrl, File queryFile) {
98
    log.debug("constructor called");
99
    this.METACATURL = metacatUrl;
100
    this.MCPASS = mcPass;
101
    this.MCUSER = mcUser;
102
    this.QUERYFILE = queryFile;
103

  
104

  
105
    log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
106
    log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
107
    log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
108
    log.warn("METACATURL: " + METACATURL 
109
            +"\nMCPASS: " + MCPASS
110
            +"\nMCUSER: " + MCUSER
111
            +"\nQUERYFILE: " + QUERYFILE);
112
    log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
113
    log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
114
    log.warn("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
115
  }
116

  
117
  public String execute() throws IOException {
118
    FileReader queryFileReader = new FileReader(QUERYFILE);
119
    String res = runQuery((Reader) queryFileReader);
120
     return res;
121
  } 
122
  
123
  
124
  /**
125
   * returns the dataset constained by the input cartesian boundaries 
126
   *
127
   * param _xmin -- the minimum x cartesian boundary
128
   * param _ymin -- the minimum y cartesian boundary
129
   * param _xmax -- the maximum x cartesian boundary
130
   * param _ymax -- the maximum y cartesian boundary
131
   *
132
   * returns data -- a Metacat spatial dataset, containing all the documents 
133
   * within the input bounding box
134
   */
135
  protected MetacatSpatialDataset queryDatasetByCartesianBounds(float
136
                                                                  _xmin,
137
                                                                  float
138
                                                                  _ymin,
139
                                                                  float
140
                                                                  _xmax,
141
                                                                  float
142
                                                                  _ymax) {
143

  
144
    MetacatSpatialDataset _data = new MetacatSpatialDataset();
145

  
146
    // get all docid's 
147
    Vector _docs = queryAllDocids();
148

  
149
    // for each, see if they fall w/in bounds
150
    for (int i = 0; i < _docs.size(); i++) {
151

  
152
    MetacatSpatialExtents _extents = new MetacatSpatialExtents();
153
      float _docMaxY =
154
          queryNorthBoundingCoordinate((String) _docs.elementAt(i));
155
      float _docMinY =
156
          querySouthBoundingCoordinate((String) _docs.elementAt(i));
157
      float _docMaxX =
158
          queryEastBoundingCoordinate((String) _docs.elementAt(i));
159
      float _docMinX =
160
          queryWestBoundingCoordinate((String) _docs.elementAt(i));
161

  
162
      //String _title = getTitle((String) _docs.elementAt(i));
163

  
164
      // check if inside the bounding box
165
      if (_docMaxX <= _xmax && _docMinX >= _xmin && _docMaxY <= _ymax && _docMinY >= _ymin ) {
166
        MetacatSpatialDocument _doc =
167
            new MetacatSpatialDocument((String) _docs.elementAt(i));
168
        
169
        log.warn("----------------------------------------------------------");
170
        log.warn("----------------------------------------------------------");
171
        log.warn("-----Spatially Selected Document: "
172
                +(String) _docs.elementAt(i)+"-----");
173
        log.warn(_docMinX+ " "+  _docMinY + " " +_docMaxX+ " " + _docMaxY);
174
        log.warn("----------------------------------------------------------");
175
        log.warn("----------------------------------------------------------");
176

  
177
        
178
        _doc.setDocid((String) _docs.elementAt(i));
179
        _extents.setXMin(_docMinX);
180
        _extents.setYMin(_docMinY);
181
        _extents.setXMax(_docMaxX);
182
        _extents.setYMax(_docMaxY);
183
        
184
        
185
        // set it as a point -- if it is one
186
        if ( _xmax==_xmin && _ymax==_ymin ) {
187
          _extents.setIsPoint(true);
188
        } else {
189
          _extents.setIsPoint(false);
190
        }
191
                
192
        // set the extents
193
        _doc.setExtents(_extents);
194
        _data.add(_doc);
195
      }
196
    }
197
    return _data;
198
  }
199

  
200
  
201
  
202
  /**
203
   * Returns a Vector of all the docids in the xml_nodes tables
204
   */
205
  protected Vector queryAllDocids() {
206
    Vector _docs = new Vector();
207
    PreparedStatement pstmt = null;
208
    ResultSet rs = null;
209
    String query = "select distinct docid from xml_nodes";
210

  
211
    try {
212
      pstmt = dbconn.prepareStatement(query);
213
      pstmt.execute();
214
      rs = pstmt.getResultSet();
215
      while (rs.next()) {
216
        String docid = rs.getString(1);
217
        log.fatal("adding docid: " + docid);
218
        _docs.add(docid);
219
      }
220
      rs.close();
221
      pstmt.close();
222
    }
223
    catch(Exception e) {
224
      log.error("Error getting docids from queryAllDocids");
225
      e.printStackTrace();
226
    }
227
    return _docs;
228
  }
229

  
230
  /**
231
   * returns the north bounding coordinate -- this is a single point
232
   */
233
  private String getTitle(String docid) {
234
    String title = null;
235
    PreparedStatement pstmt = null;
236
    ResultSet rs = null;
237
    String query = "select docid, nodedata, nodeid from xml_nodes where "
238
        + "nodeid =(select  nodeid from  xml_nodes where docid  like '"
239
        + docid.trim() + "' and nodename like 'title%');";
240
    try {
241
      pstmt = dbconn.prepareStatement(query);
242
      pstmt.execute();
243
      rs = pstmt.getResultSet();
244
      if (rs.next())
245
        title = rs.getString(2);
246
      rs.close();
247
      pstmt.close();
248
    }
249
    catch(Exception e) {
250
      log.error("Error getting docids from queryExtentsByDocid");
251
      e.printStackTrace();
252
    }
253
    return title;
254
  }
255

  
256
  /**
257
   * returns the north bounding coordinate -- this is a single point
258
   */
259
  private float queryNorthBoundingCoordinate(String docid) {
260
    float _coord = MetacatSpatialConstants.FLOAT_NULL;
261
    PreparedStatement pstmt = null;
262
    ResultSet rs = null;
263
    String query = "select max(nodedata) from xml_nodes where "
264
        + "parentnodeid in (select  nodeid from  xml_nodes where docid  like '"
265
        + docid.trim() + "' and nodename like 'northBoundingCoordinate');";
266

  
267
    try {
268
      pstmt = dbconn.prepareStatement(query);
269
      pstmt.execute();
270
      rs = pstmt.getResultSet();
271
      if (rs.next())
272
        _coord = rs.getFloat(1);
273
      rs.close();
274
      pstmt.close();
275
    }
276
    catch(Exception e) {
277
      log.error("Error getting docids from queryExtentsByDocid");
278
      e.printStackTrace();
279
    }
280
    return _coord;
281
  }
282

  
283

  
284
  /**
285
   * returns the east bounding coordinate -- this is a single point
286
   */
287
  private float queryEastBoundingCoordinate(String docid) {
288
    float _coord = MetacatSpatialConstants.FLOAT_NULL;
289
    PreparedStatement pstmt = null;
290
    ResultSet rs = null;
291
    String query = "select max(nodedata) from xml_nodes where "
292
        + "parentnodeid in (select  nodeid from  xml_nodes where docid  like '"
293
        + docid.trim() + "' and nodename like 'eastBoundingCoordinate');";
294

  
295
    try {
296
      pstmt = dbconn.prepareStatement(query);
297
      pstmt.execute();
298
      rs = pstmt.getResultSet();
299
      if (rs.next())
300
        _coord = rs.getFloat(1);
301
      rs.close();
302
      pstmt.close();
303
    }
304
    catch(Exception e) {
305
      log.error("Error getting docids from queryExtentsByDocid");
306
      e.printStackTrace();
307
    }
308
    return _coord;
309
  }
310

  
311

  
312
  /**
313
   * returns the south bounding coordinate -- this is a single point
314
   */
315
  private float querySouthBoundingCoordinate(String docid) {
316
    float _coord = MetacatSpatialConstants.FLOAT_NULL;
317
    PreparedStatement pstmt = null;
318
    ResultSet rs = null;
319
    String query = "select max(nodedata) from xml_nodes where "
320
        + "parentnodeid in (select  nodeid from  xml_nodes where docid  like '"
321
        + docid.trim() + "' and nodename like 'southBoundingCoordinate');";
322

  
323
    try {
324
      pstmt = dbconn.prepareStatement(query);
325
      pstmt.execute();
326
      rs = pstmt.getResultSet();
327
      if (rs.next())
328
        _coord = rs.getFloat(1);
329
      rs.close();
330
      pstmt.close();
331
    }
332
    catch(Exception e) {
333
      log.error("Error getting docids from queryExtentsByDocid");
334
      e.printStackTrace();
335
    }
336
    return _coord;
337
  }
338

  
339

  
340

  
341
  /**
342
   * returns the west bounding coordinate -- this is a single point
343
   */
344
  private float queryWestBoundingCoordinate(String docid) {
345
    float _coord = MetacatSpatialConstants.FLOAT_NULL;
346
    PreparedStatement pstmt = null;
347
    ResultSet rs = null;
348
    String query = "select max(nodedata) from xml_nodes where "
349
        + "parentnodeid in (select  nodeid from  xml_nodes where docid  like '"
350
        + docid.trim() + "' and nodename like 'westBoundingCoordinate');";
351
        
352
     log.warn("issuing query: " + query);
353

  
354
    try {
355
      pstmt = dbconn.prepareStatement(query);
356
      pstmt.execute();
357
      rs = pstmt.getResultSet();
358
      if (rs.next())
359
        _coord = rs.getFloat(1);
360
      rs.close();
361
      pstmt.close();
362
    }
363
    catch(Exception e) {
364
      log.error("Error getting docids from queryWestBoundingCoordinate");
365
      e.getMessage();
366
    }
367
    return _coord;
368
  }
369

  
370

  
371

  
372

  
373
  /**
374
   * Performs a spatial query given the docid as an input
375
   * 
376
   * @param docid -- the docid for which the extents are to be queried
377
   * @returns spatialextents -- the MetcataSpatialExtents object for this query
378
   */
379
  protected MetacatSpatialExtents queryExtentsByDocid(String docid) {
380
    MetacatSpatialExtents _extents = new MetacatSpatialExtents();
381

  
382
    float _northbc = queryNorthBoundingCoordinate(docid);
383
    float _eastbc = queryEastBoundingCoordinate(docid);
384
    float _southbc = querySouthBoundingCoordinate(docid);
385
    float _westbc = queryWestBoundingCoordinate(docid);
386

  
387
    if ((_northbc == _southbc) && (_eastbc == _westbc)) {
388
      _extents.setIsPoint(true);
389
    } else {
390
      _extents.setIsPoint(false);
391
    }
392

  
393
    _extents.setYMin((_southbc < _northbc ? _southbc : _northbc));
394
    _extents.setYMax((_southbc > _northbc ? _southbc : _northbc));
395
    _extents.setXMin((_westbc < _eastbc ? _westbc : _eastbc));
396
    _extents.setXMax((_westbc > _eastbc ? _westbc : _eastbc));
397

  
398
    _extents.setDocid(docid);
399

  
400
    return _extents;
401
  }
402

  
403

  
404
        /**
405
		* Query the Metacat Server to get a list of documents, 
406
		* if it doesn't exist there, from the backend storage server.
407
		* 
408
		* @param query the xml description of the query to run
409
		* @return String the XML document string of the result set
410
		* @throws QueryFailedException when any thing happens to prevent a query
411
		*  returns
412
		*/
413
  private String runQuery(Reader query) {
414
    String document = null;
415

  
416
    Reader xdoc = null;
417
    String error = null;
418
    try {
419
      log.debug("creating metacat instance with: " + METACATURL);
420
      Metacat m = MetacatFactory.createMetacatConnection(METACATURL);
421
      m.login(MCUSER, MCPASS);
422
      log.debug("metacat instance: " + m);
423
      xdoc = m.query(query);
424
      document = IOUtil.getAsString(xdoc, true);
425
      m.logout();
426
      if (document == null) {
427
        throw new QueryFailedException("Document String Was null");
428
      }
429
    }
430
    catch(Exception e) {
431
      e.printStackTrace();
432
    }
433
    return document;
434
  }
435

  
436

  
437
}
438 0

  
src/edu/ucsb/nceas/metacat/spatial/SpatialQueryManager.java
1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2003 Regents of the University of California.
4
 *
5
 *   '$Author$'
6
 *     '$Date$'
7
 * '$Revision$'
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
import java.io.FileReader;
27
import java.io.PrintWriter;
28
import java.io.IOException;
29
import java.io.StringReader;
30
import java.io.BufferedReader;
31
import java.io.Reader;
32
import java.io.FileInputStream;
33
import java.io.BufferedInputStream;
34
import java.util.Enumeration;
35
import java.util.Hashtable;
36
import java.util.ResourceBundle;
37
import java.util.Random;
38
import java.util.StringTokenizer;
39
import java.util.Properties;
40
import java.util.PropertyResourceBundle;
41
import java.util.Vector;
42
import java.util.Map;
43

  
44
import java.net.MalformedURLException;
45
import java.sql.PreparedStatement;
46
import java.sql.ResultSet;
47
import java.sql.Connection;
48
import java.sql.SQLException;
49
import java.lang.reflect.*;
50
import java.net.*;
51
import java.util.zip.*;
52

  
53
import javax.servlet.ServletConfig;
54
import javax.servlet.ServletContext;
55
import javax.servlet.ServletException;
56
import javax.servlet.ServletInputStream;
57
import javax.servlet.http.HttpServlet;
58
import javax.servlet.http.HttpServletRequest;
59
import javax.servlet.http.HttpServletResponse;
60
import javax.servlet.http.HttpSession;
61
import javax.servlet.http.HttpUtils;
62
import javax.servlet.ServletOutputStream;
63

  
64
import edu.ucsb.nceas.metacat.client.Metacat;
65
import edu.ucsb.nceas.metacat.client.MetacatFactory;
66
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
67
import edu.ucsb.nceas.metacat.client.MetacatException;
68
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
69
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
70
import edu.ucsb.nceas.utilities.IOUtil;
71

  
72
import org.apache.log4j.Logger;
73
import org.apache.log4j.BasicConfigurator;
74
import org.apache.log4j.PropertyConfigurator;
75

  
76

  
77

  
78
/**
79
 * An application that manages the registration of ecological networks using the
80
 * metacat technology
81
 */
82
public class SpatialQueryManager extends HttpServlet
83
{
84

  
85
  private ServletConfig config = null;
86
  private ServletContext context = null;
87
  private Properties appConfig = null;
88
  private static final String CONFIG_DIR = "WEB-INF";
89
  private static final String CONFIG_NAME = "econet.properties";
90
  private static final String STYLE_DIR = "WEB-INF/";
91
  private String defaultStyle = null;
92
  private String metacatUrl = null;
93
  private String queryName = null;
94
  private String invalidRegistrationErrorPage = null;
95

  
96
// private EcoNetwork network;
97

  
98
  private String mcUser = "uid=jones,o=NCEAS,dc=ecoinformatics,dc=org";
99
  private String mcPass = "@mcpass@";
100

  
101
//	private  EconetCache cache;
102
	
103
  protected SpatialQueryProcessor queryProcessor;
104
	// this is the key val for the econet summary to be in the cache and 
105
	// it must be the same value as the value in the manager
106
//	private static String ECONET_SUMMARY_KEY = "econet_summary"; 
107

  
108
  private static Logger log = Logger.getLogger(SpatialQueryManager.class.getName());
109

  
110
  /**
111
   * Initialize the servlet during container startup
112
   */
113
  public void init(ServletConfig config) throws ServletException
114
  {
115
    try
116
    {
117
      super.init(config);
118
      this.config = config;
119
      this.context = config.getServletContext();
120

  
121
      //BasicConfigurator.configure();
122
      String prefix = getServletContext().getRealPath("/");
123
      System.out.println("SpatialQueryManager servlet context path  ####################### >>> " + prefix);
124
      String file = getInitParameter("log4j-init-file");
125
      System.out.println("SpatialQueryManager log4j-init-file  ####################### >>> " + file);
126
      System.out.println("SpatialQueryManager econet - metacat acct:  ####################### >>> " + mcUser);
127
      
128
      // if the log4j-init-file is not set, then no point in trying
129
      if (file != null)
130
      {
131
        PropertyConfigurator.configure(prefix + file);
132
      }
133

  
134
      try
135
      {
136
        // locate, open, and read the properties
137
        appConfig = new Properties();
138
        String dirPath = context.getRealPath(CONFIG_DIR);
139
        File propertyFile = new File(dirPath, CONFIG_NAME);
140
        FileInputStream fis = new FileInputStream(propertyFile);
141
				appConfig.load(fis);
142
				fis.close();
143
				defaultStyle = (String) appConfig.get("defaultStyle");
144
				metacatUrl = (String) appConfig.get("metacatUrl");
145
				System.out.println("SpatialQueryManager using metacat at url:  ####################### >>> " + metacatUrl);
146
				queryName = (String)appConfig.get("queryName");
147
				System.out.println("SpatialQueryManager query name :  ####################### >>> " + queryName);
148
				invalidRegistrationErrorPage = (String) appConfig.get("invalidRegistrationErrorPage");
149

  
150
      }
151
      catch(Throwable t)
152
      {
153
        throw new ServletException(t.getMessage());
154
      }
155
    }
156
    catch(ServletException ex) {
157
      throw ex;
158
    }
159
  }
160

  
161
  /** Handle "GET" method requests from HTTP clients */
162
  public void doGet(HttpServletRequest request, HttpServletResponse response)
163
  throws ServletException, IOException
164
  {
165
    handleGetOrPost(request, response);
166
  }
167

  
168
  /** Handle "POST" method requests from HTTP clients */
169
  public void doPost(HttpServletRequest request, HttpServletResponse response)
170
  throws ServletException, IOException
171
  {
172
    handleGetOrPost(request, response);
173
  }
174

  
175
  /**
176
   * Control servlet response depending on the action parameter specified
177
   */
178
  private void handleGetOrPost(HttpServletRequest request, HttpServletResponse response)
179
  throws ServletException, IOException
180
  {
181
    Hashtable params = getParamHash(request);
182
    String action = getAction(request);
183
      log.debug(">> action " + action);
184

  
185
    if (action.equals("list")) {
186
      handleListAction(request, response);
187
    } else if (action.equals("register")) {
188
      //handleRegisterAction(request, response);
189
    } else if (action.equals("delete")) {
190
      handleDeleteAction(request, response);
191
    } else if (action.equals("displaydoc")) {
192
      handleDisplayDocAction(request, response);
193
    } else {
194
      handleListAction(request, response);
195
    }
196
  }
197

  
198
  /**
199
    * Reads a document from metacat and displays the information to the browser
200
    * @param request -- the HTTP request object
201
    * @param response -- the HTTP response object
202
    */
203
  private void handleDisplayDocAction(HttpServletRequest request, HttpServletResponse response)
204
  throws IOException
205
  {
206
    Hashtable params = getParamHash(request);
207
    String contextPath = request.getContextPath();
208
    String action = getAction(request);
209
    String styleSystemId = getStyleSystemId(action, defaultStyle);
210
    String docid = (String) getParamHash(request).get("docId");
211
    PrintWriter out = response.getWriter();
212
    ServletContext servletContext = getServletContext();
213
    response.setContentType ("text/html");
214
    if (docid != null && !docid.trim().equals(""))
215
    {
216
      try {
217
				String doc = null;
218
	//			if ( cache.recover(docid) == null ) {
219
					log.debug("docid in the cache is null ... going to the db");
220
					Metacat m = MetacatFactory.createMetacatConnection(metacatUrl);
221
					m.login(mcUser, mcPass);
222
					Reader r = m.read(docid);
223
					doc = IOUtil.getAsString(r, true);
224
					r.close();
225
					m.logout();
226
					// adding this was giving a concurrent modification exception
227
					//cache.admit(docid, doc);
228
	//			} else {
229
//					log.debug("docid in the cache is valid");
230
//					doc = (String)cache.recover(docid);
231
//				}
232
        String dirPath = context.getRealPath(CONFIG_DIR);
233
				XSLTransform.transform(doc, styleSystemId, out, params);
234
				out.close();	
235
      }
236
      catch(Exception e) { e.printStackTrace(); }
237
    } else {
238
      out.println("no such docid!");
239
    }
240
    out.close();
241
  }
242

  
243
  /**
244
    * Deletes a network from the registration system.  This is called by the 
245
    * administrator to delete a registry from metacat. There is no response to 
246
    * the calling device - instead details are written to the logger 
247
    * @param request -- the HTTP request object
248
    * @param response -- the HTTP response object
249
    */
250
  private void handleDeleteAction(HttpServletRequest request, HttpServletResponse response) throws IOException
251
  {
252
    Hashtable params = getParamHash(request);
253
    String docId = (String)params.get("docId");
254
    // for the Metacat.delete request to be called the password needs to be the 
255
    // same as the mcpass var.
256
    String pass = (String)params.get("password");
257
    if ( params.containsKey("password") ) {
258
      if ( pass.equals(mcPass) ) {
259
        log.info(">> deleting docid: " + docId);
260
        // add a lookup for an issued password.
261
        try
262
        {
263
         Metacat m = MetacatFactory.createMetacatConnection(metacatUrl);
264
         log.info(mcUser + " " + mcPass);
265
         m.login(mcUser, mcPass);
266
         String resp = m.delete(docId);
267
         log.info(">>deletion success is: " + resp);
268
        }
269
        catch(Exception e) { e.printStackTrace(); }
270
      }
271
    else { log.fatal("attempt to delete a registry with invalid pass"); }
272
    }
273
    else { log.fatal("attempt to delete a registry with NO pass"); }
274
  }
275

  
276
  /**
277
    *  Display the registered networks.  This is called when a list of 
278
    * regestered networks is requested for display and a transformation
279
    * is needed.  It queries the registered networks and then transforms the 
280
    * network docs using XSLT and displays the networks.
281
    * @param request -- the HTTP request object
282
    * @param response -- the HTTP response object
283
    */
284
  private void handleListAction(HttpServletRequest request, HttpServletResponse response) throws IOException
285
  {
286
    Hashtable params = getParamHash(request);
287
    String contextPath = request.getContextPath();
288
    String action = getAction(request);
289
    String styleSystemId = getStyleSystemId(action, defaultStyle);
290

  
291
    //String style = (String)pathData.get(1);
292
    PrintWriter out = response.getWriter();
293
    ServletContext servletContext = getServletContext();
294
    response.setContentType ("text/html");
295

  
296
    // get the query document
297
    String dirPath = context.getRealPath(CONFIG_DIR);
298
    File queryFile = new File(dirPath, queryName);
299
    // Query for the documents from the server
300
    String queryResult = null;
301
    try {
302
      // if the cache doesnt have the summary then get it from the database
303
//		if ( cache.recover(ECONET_SUMMARY_KEY) == null ) {
304
//			log.debug("summary in the cache is null ... going to the db");
305
				queryResult = queryProcessor.execute();
306
//				cache.admit(ECONET_SUMMARY_KEY, queryResult);
307
//			} else {
308
//				log.debug("summary in the cache is valid");
309
//				queryResult = (String)cache.recover(ECONET_SUMMARY_KEY);
310
//			}
311
    } catch(Exception e) { e.printStackTrace(); }
312
    
313
    log.debug("query result >> " + queryResult);
314
    XSLTransform.transform(queryResult, styleSystemId, out, params);
315
    out.close();
316
  }
317

  
318

  
319

  
320
  /**
321
    *  Register the network.  This is called when the attributes of a network 
322
    *  are submitted to the system.
323
    *
324
    * @param request -- the HTTP request object
325
    * @param response -- the HTTP response object
326
    */
327
/**  private void handleRegisterAction(HttpServletRequest request, HttpServletResponse response) throws IOException
328
  {
329
    Map params = getParamHash(request);
330
    String contextPath = request.getContextPath();
331
    String action = getAction(request);
332
    
333
    network = new EcoNetwork((Map) params);
334
    // add a validation step here 
335
    if (network.isValid() == true)
336
    {
337
      PrintWriter out = response.getWriter();
338
      response.setContentType ("text/html");
339
        log.info("about to insert: " + network.toXML());
340
      String metacatResponse = insertEcoNetwork(network.toXML());
341
        log.info("metacat response: " + metacatResponse);
342

  
343
      String styleSystemId = getStyleSystemId(action, defaultStyle);
344
        log.info("registration system id  " + styleSystemId);
345
        XSLTransform.transform(metacatResponse, styleSystemId, out, (Hashtable) params);
346
				
347
        // clear the summary from the cache which will be recovered either next
348
        // time the show all docs function is called or the ttl in the cache is
349
        // achived.
350
				cache.clear();
351
        
352
        out.close();
353
    } else
354
    {
355
      //redirect somewhere
356
      response.sendRedirect(invalidRegistrationErrorPage);
357
    }
358
  }
359
**/
360

  
361

  
362
    /**
363
      * Inserts the registration document to metacat.  After the registration
364
      * has been processed and validated the XML representation is submitted
365
      * to the metacat system
366
      *  @param networkXML -- the xml document containing the econetwork 
367
      *     data represented as a java string. 
368
      *  @return metacatResponse -- the response from metacat
369
      */
370
/**  private String insertEcoNetwork(String networkXML)
371
  {
372
    String error = null;
373
    String response = null;
374
    try {
375
      Metacat m = MetacatFactory.createMetacatConnection(metacatUrl);
376
      log.info(mcUser + " " + mcPass);
377
      m.login(mcUser, mcPass);
378
      int i = (int) (java.lang.Math.random() * 1000);
379
      log.info(" inserting document: " + "econet." + i + ".1");
380
      response = m.insert("econet." + i + ".1", new StringReader(networkXML), null);
381
      log.info(" metacat response: " + response);
382
    }
383
    catch(Exception e) {
384
      e.printStackTrace();
385
    }
386
    return response;
387
  }
388
**/
389

  
390

  
391
  /**
392
    * Gets the "action" parameter from the http request object
393
    * @param request -- the http request object
394
    * @return action -- the action requested of this servlet 
395
    */
396
  private String getAction(HttpServletRequest request)
397
  throws NullPointerException
398
  {
399
    String action = (String) getParamHash(request).get("action");
400
      return action;
401
  }
402

  
403
  /**
404
     * Get the stylesheet systemid from the properties file for a given
405
     * action and style set.
406
     *
407
     * @param action the servlet request action
408
     * @param style the name of the style to be used
409
     * @return a String containing the system id of the stylesheet to be used
410
     */
411
  private String getStyleSystemId(String action, String style)
412
  throws IOException
413
  {
414
    String key = action + "." + style;
415
    //log.info("key >>" + key);
416
    String filename = (String) appConfig.get(key);
417
    //log.info("filename >>" + filename);
418
    String stylePath = context.getRealPath(STYLE_DIR);
419
    //log.info("stylePath>>" + stylePath);
420
    File xslFile = new File(stylePath, filename);
421
    String systemId = xslFile.getCanonicalPath();
422
      systemId = "file://" + systemId;
423
      log.info("returning systemId >> " + systemId + " for action.style: " + key);
424
      return systemId;
425
  }
426

  
427
  /**
428
    * utility function to convert the request object into a hashtable 
429
    * @param request -- the http request object
430
    * @return paramHash -- hashtable containing the name-value pairs
431
    */
432
  private Hashtable getParamHash(HttpServletRequest request)
433
  {
434
    Hashtable params = new Hashtable();
435
    try {
436
      Enumeration _enum = request.getParameterNames();
437
      while (_enum.hasMoreElements()) {
438
        String name = (String) _enum.nextElement();
439
        String values[] = request.getParameterValues(name);
440
        if (values != null) {
441
          for (int i = 0; i < values.length; i++) {
442
            params.put(name, values[i]);
443
          }
444
        }
445
      }
446
    }
447
    catch(Exception e) {
448
      e.printStackTrace();
449
    }
450
    return (params);
451
  }
452

  
453
}
454 0

  
src/edu/ucsb/nceas/metacat/spatial/SpatialHarvester.java
35 35
import edu.ucsb.nceas.metacat.DBConnection;
36 36
import org.geotools.feature.Feature;
37 37

  
38
/* 
39
 * Harvests spatial data from metacat and saves to persistent cache
38
/** 
39
 * Harvests spatial data from metacat database
40
 * and saves to persistent cache
40 41
 */
41 42
public class SpatialHarvester {
42 43
 
......
44 45
 
45 46
  private DBConnection dbconn;
46 47
 
47
  /** constructor to initialize db connection **/
48
  /** 
49
   * constructor to initialize db connection 
50
   */
48 51
  public SpatialHarvester() {
49 52
      try {
50 53
          dbconn = new DBConnection();
......
54 57
      }
55 58
  }
56 59
 
57
  /*
58
   * Closes the database connection
59
   * MUST be called after you're done with
60
   * the SpatialHarvester
60
  /**
61
   * Closes the database connection. 
62
   * Should be called after you're done with the SpatialHarvester
61 63
   */
62 64
  public void destroy() {
63 65
      try {
64 66
          dbconn.close();
65 67
      } catch( Exception e ) {
66
          log.error("Error closing out dbconn");
68
          log.error("Error closing out dbconn in spatial harvester");
67 69
          e.printStackTrace();
68 70
      }
69 71
  }
......
97 99
    return _docs;
98 100
  }
99 101

  
100
  /*
101
   * Currently just a wrapper around the harvester
102
  /**
103
   * Currently just a wrapper around the harvestDocument method.
102 104
   * Eventually we can use this method as a
103
   * timed que like the indexing process
105
   * timed que like the indexing process.
106
   *
107
   * @param docid The docid to be added to the spatial cache.
104 108
   */                   
105 109
  public void addToUpdateQue( String docid ) {
106 110
      harvestDocument(docid);
107 111
  }
108 112

  
109
  /*
110
   * Delete from spatial cache
111
   * Just a wrapper around delete for now
113
  /**
114
   * Delete a given document from spatial cache.
115
   * Just a wrapper around deleteDocument method for now.
116
   *
117
   * @param docid The docid to be deleted from the spatial cache.
112 118
   */
113 119
  public void addToDeleteQue( String docid ) {
114 120
      deleteDocument(docid);
115 121
  }
116 122

  
117
  /*
118
   * Given a docid, will attempt to delete
119
   * from spatial cache
123
  /**
124
   * Given a docid, will attempt to delete it from spatial cache
125
   *
126
   * @param docid The docid to be deleted from the spatial cache.
120 127
   */
121 128
  public void deleteDocument( String docid ) {
122 129

  
......
135 142
  }      
136 143

  
137 144

  
138
  /*
139
   * Given a docid, will update the spatial cache accordingly
145
  /**
146
   * Given a new or updated docid, 
147
   * will update the spatial cache accordingly.
148
   *
149
   * @param docid The docid to be updated or inserted into the spatial cache.
140 150
   */
141 151
  public void harvestDocument( String docid ) {
142 152

  
......
161 171
     }
162 172
  }
163 173

  
164
  /*
165
   * Completely regenerates the spatial cache
174
  /**
175
   * Completely regenerates the spatial cache. 
176
   * This can take a long time, especially with lots of documents.
166 177
   */
167 178
  public void regenerate() {
168 179
      
src/edu/ucsb/nceas/metacat/spatial/SpatialDataset.java
47 47

  
48 48
import edu.ucsb.nceas.metacat.MetaCatUtil;
49 49

  
50

  
50
/**
51
 * Class providing direct read/write access to the
52
 * persistent spatial cache.
53
 */
51 54
public class SpatialDataset {
52 55

  
53 56
  SpatialFeatureSchema featureSchema = new SpatialFeatureSchema();
......
61 64
  private static Logger log =
62 65
      Logger.getLogger(SpatialDataset.class.getName());
63 66

  
64
  /** empty constructor **/
67
  /**
68
   *  empty constructor for SpatialDataset
69
   */
65 70
  public SpatialDataset() {
66 71
    
67 72
  }
68 73

  
69
  /*
74
  /**
70 75
   * Adds a new feature (from a SpatialDocument)
71 76
   * This is faster than insertOrUpdate but 
72 77
   * relying on this method might cause duplication
73 78
   * of docids in the spatial cache. Therefore, its really only useful when 
74 79
   * regenerating the entire cache.
80
   *
81
   * @param geomType The kind of feature to be added. Currently "polygon" and "point" supported.
82
   * @param feature The geotools feature to be added to the spatial cache.
75 83
   */ 
76 84
  public void add( String geomType, Feature feature ) {
77 85
     if( geomType.equals("polygon") ) {
......
86 94
     }
87 95
  }
88 96

  
89
  /*
97
  /**
90 98
   * Deletes given docid from the spatial cache.
99
   *
100
   * @param geomType The kind of feature to be added. Currently "polygon" and "point" supported.
101
   * @param docid The document to be deleted from the spatial cache.
91 102
   */
92 103
  public void delete( String geomType, String docid ) throws IOException {
93 104

  
......
150 161

  
151 162
  }
152 163

  
153
  /*
164
  /**
154 165
   * Either inserts or updates the spatial cache with the new
155 166
   * spatial document depending on if it currently exists.
156 167
   * Docid is also passed in for quicker searching.
168
   *
169
   * @param geomType The kind of feature to be added. Currently "polygon" and "point" supported.
170
   * @param feature The geotools feature to be added to the spatial cache.
171
   * @param docid The document id to be inserted or updated. Used to filter for existing features.
157 172
   */
158 173
  public void insertOrUpdate( String geomType, Feature feature, String docid ) throws IOException {
159 174
    
......
227 242

  
228 243
  }
229 244

  
230
  /*
231
   * Saves the SpatialDataset object to the spatial cache
245
  /**
246
   * Saves the SpatialDataset object to the spatial cache.
232 247
   */
233 248
  public void save() {
234 249
         // Save Polygons 
src/edu/ucsb/nceas/metacat/spatial/SldFactory.java
32 32

  
33 33
import org.w3c.dom.*;
34 34

  
35
/**
36
 * Class to generate Styled Layer Descriptors allowing geoserver to 
37
 * filter the feature rendering based on various contraints 
38
 * such as permissions, non-spatial queries and skin configuration.
39
 */
35 40
public class SldFactory extends HttpServlet {
36 41
  
37 42
  static Document document;
38 43
  static String sld;
39 44
  
40
  /** Handle "GET" method requests from HTTP clients */
45
  /** 
46
   * Handle "GET" method requests from HTTP clients 
47
   *
48
   * @param request Incoming servlet request.
49
   * @param response Servlet response.
50
   */
41 51
  public void doGet(HttpServletRequest request, HttpServletResponse response)
42 52
  throws ServletException, IOException
43 53
  {
44 54
    handleGetOrPost(request, response);
45 55
  }
46 56

  
47
  /** Handle "POST" method requests from HTTP clients */
57
  /** 
58
   * Handle "POST" method requests from HTTP clients 
59
   *
60
   * @param request Incoming servlet request.
61
   * @param response Servlet response.
62
   */
48 63
  public void doPost(HttpServletRequest request, HttpServletResponse response)
49 64
  throws ServletException, IOException
50 65
  {
......
53 68

  
54 69
  /**
55 70
   * Control servlet response depending on the action parameter specified
71
   * Modifies the original SLD according to various access contraints
72
   * and sends it as the servlet response.
73
   *
74
   * @param request Incoming servlet request.
75
   * @param response Servlet response.
76
   * @todo Determine filename from variables in metacat.properties.
56 77
   */
57 78
  private void handleGetOrPost(HttpServletRequest request, HttpServletResponse response)
58 79
  throws ServletException, IOException
......
76 97
   * returns SLD document as a String.
77 98
   * 
78 99
   * @param filename	Filename of the base sld.
79
   * 
100
   * @todo Implement the doc id list queries for contraints.
80 101
   */
81 102
  private String getSld(String filename)
82 103
  {
src/edu/ucsb/nceas/metacat/spatial/SpatialFeatureSchema.java
34 34

  
35 35
import org.apache.log4j.Logger;
36 36

  
37

  
37
/**
38
 * Class representing the geotools feature schemas and file paths
39
 * for the spatial data cache.
40
 */
38 41
public class SpatialFeatureSchema {
39 42

  
40 43
  private static Logger log =
......
51 54
         
52 55
  }
53 56

  
54
  /*
57
  /**
55 58
   * Creates the featuretype schema for polygon bounds
56 59
   */
57 60
  public static FeatureType getPolygonFeatureType() {
......
69 72
    }
70 73
  }
71 74

  
72
  /*
75
  /**
73 76
   * Creates the featuretype schema for point centroids
74 77
   */
75 78
  public static FeatureType getPointFeatureType() {
src/edu/ucsb/nceas/metacat/spatial/SpatialDocument.java
48 48

  
49 49
import org.apache.log4j.Logger;
50 50

  
51
/**
52
 * Class representing the spatial portions of an xml document
53
 * as a geotools Feature.
54
 */
51 55
public class SpatialDocument {
52 56

  
53 57
  private DBConnection dbconn;
......
65 69
  String title = null;
66 70
  String docid = null;
67 71

  
68
  /** constructor that queries the db **/
72
  /** 
73
   * Constructor that queries the db 
74
   *
75
   * @param docid The document id to be represented spatially
76
   * @param dbconn The database connection shared from the refering method.
77
   * @todo Rewrite the title query to use xml_path_index
78
   */
69 79
  public SpatialDocument( String docid , DBConnection dbconn ) {
70 80

  
71 81
    this.docid = docid;
......
108 118
      e.printStackTrace();
109 119
    }      
110 120

  
111
    // Get the Title
112
    query = "select docid, nodedata, nodeid "
113
          + "from xml_nodes "
114
          + "where parentnodeid = "
115
          + "  ( select  nodeid "
116
          + "    from  xml_nodes "
117
          + "    where docid like '" + docid.trim() +"' "
118
          + "    and nodename like 'title%' "
119
          + "    and parentnodeid = "
120
          + "      ( select nodeid "
121
          + "        from xml_nodes "
122
          + "        where docid like '" + docid.trim() + "' "
123
          + "        and nodename = 'dataset' "
124
          + "        limit 1) "
125
          + "    limit 1)" ;
121
    /*
122
     * Get the title
123
     */
124
    String docTitlePath = MetaCatUtil.getOption("docTitle");
125
    query = "select nodedata from xml_path_index where path = '" 
126
          + docTitlePath + "' and docid = '" + docid.trim() + "'";
126 127

  
127 128
    try {
128 129
      pstmt = dbconn.prepareStatement(query);
129 130
      pstmt.execute();
130 131
      rs = pstmt.getResultSet();
131 132
      if (rs.next())
132
        this.title = rs.getString(2);
133
        this.title = rs.getString(1);
133 134
      rs.close();
134 135
      pstmt.close();
135 136
    }
......
149 150

  
150 151
  }
151 152

  
152
  /* 
153
   * Returns a jts (multi)polygon feature with geometry plus attributes
153
  /** 
154
   * Returns a geotools (multi)polygon feature with geometry plus attributes
154 155
   * ready to be inserted into our spatial dataset cache
155 156
   */
156 157
  public Feature getPolygonFeature() {
......
175 176
      }
176 177
  }
177 178

  
178
  /* 
179
   * Returns a jts (multi)point feature with geometry plus attributes
179
  /**
180
   * Returns a geotools (multi)point feature with geometry plus attributes
180 181
   * ready to be inserted into our spatial dataset cache
182
   *
181 183
   */
182 184
  public Feature getPointFeature() {
183 185
      // Get polygon feature type
......
201 203
      }
202 204
  }
203 205

  
204
  /*
206
  /**
205 207
   * Given a valid docid, return an appropriate URL
206 208
   * for viewing the metadata document
209
   *
210
   * @param docid The document id for which to construct the access url.
207 211
   */
208 212
  private String getUrl( String docid ) {
209 213
     String docUrl = MetaCatUtil.getOption("metacatUrl")  
......
214 218
     return docUrl;
215 219
  }
216 220

  
221

  
217 222
  /**
218
   * returns the title of the docid
219
   */
220
  private String getTitle(String docid) {
221
    String title = null;
222
    PreparedStatement pstmt = null;
223
    ResultSet rs = null;
224
    String query = "select docid, nodedata, nodeid "
225
                 + "from xml_nodes "
226
                 + "where parentnodeid = "
227
                 + "  ( select  nodeid "
228
                 + "    from  xml_nodes "
229
                 + "    where docid like '" + docid.trim() +"' "
230
                 + "    and nodename like 'title%' "
231
                 + "    and parentnodeid = "
232
                 + "      ( select nodeid "
233
                 + "        from xml_nodes "
234
                 + "        where docid like '" + docid.trim() + "' "
235
                 + "        and nodename = 'dataset' "
236
                 + "        limit 1) "
237
                 + "    limit 1)" ;
238

  
239
    /*
240
     * String query = "select docid, nodedata, nodeid from xml_nodes where "
241
     *   + "nodeid =(select  nodeid from  xml_nodes where docid  like '"
242
     *   + docid.trim() + "' and nodename like 'title%');";
243
     */
244

  
245
    try {
246
      dbconn = new DBConnection();
247
      pstmt = dbconn.prepareStatement(query);
248
      pstmt.execute();
249
      rs = pstmt.getResultSet();
250
      if (rs.next())
251
        title = rs.getString(2);
252
      rs.close();
253
      pstmt.close();
254
      dbconn.close();
255
    }
256
    catch(Exception e) {
257
      log.error(" **** Error getting docids from getTitle for docid = "+docid);
258
      e.printStackTrace();
259
      log.error(" query ============== \n " + query);
260
      title = docid;
261
    }
262
    
263
    return title;
264
  }
265

  
266

  
267
  /*
268 223
   * Returns a mutlipolygon geometry representing the geographic coverage(s) of the document
224
   *
269 225
   */
270 226
  private MultiPolygon getPolygonGeometry() {
271 227

  
......
337 293
  }
338 294
   
339 295

  
340
  /*
341
   * returns a polygon given the four bounding box coordinates
296
  /**
297
   * Returns a polygon given the four bounding box coordinates
342 298
   */
343 299
  private Polygon createPolygonFromBbox( GeometryFactory geomFac, Float w, Float s, Float e, Float n ) {
344 300

  
......
354 310
  }
355 311

  
356 312

  
357
  /*
358
   * returns a point geometry
313
  /**
314
   * Returns a multipoint geometry represnting the geographic coverage(s) of the document
315
   *
316
   * @todo Handle the case of crossing the dateline and poles
359 317
   */
360 318
  private MultiPoint getPointGeometry() {
361 319

  

Also available in: Unified diff