Project

General

Profile

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

    
26
package edu.ucsb.nceas.metacattest;
27

    
28
import java.io.FileNotFoundException;
29
import java.io.IOException;
30
import java.io.StringReader;
31
import java.sql.SQLException;
32
import java.util.Calendar;
33
import java.util.Date;
34
import java.util.GregorianCalendar;
35
import java.util.HashMap;
36
import java.util.Hashtable;
37
import java.util.SimpleTimeZone;
38
import java.util.TimeZone;
39
import java.util.Vector;
40

    
41
import edu.ucsb.nceas.MCTestCase;
42
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
43
import edu.ucsb.nceas.metacat.client.Metacat;
44
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
45
import edu.ucsb.nceas.metacat.client.MetacatException;
46
import edu.ucsb.nceas.metacat.client.MetacatFactory;
47
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
48
import edu.ucsb.nceas.metacat.properties.PropertyService;
49
import edu.ucsb.nceas.utilities.FileUtil;
50
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
51
import edu.ucsb.nceas.utilities.UtilException;
52
import junit.framework.Test;
53
import junit.framework.TestSuite;
54

    
55
/**
56
 * A JUnit test for testing Access Control in Metacat
57
 */
58
public class SchemaRegistryTest extends MCTestCase {
59

    
60
	private static String metacatUrl;
61
	private static String metacatDeployDir;
62
	private static String username;
63
	private static String password;
64
	static {
65
		try {
66
			metacatUrl = PropertyService.getProperty("test.metacatUrl");
67
			metacatDeployDir = PropertyService.getProperty("test.metacatDeployDir");
68
			username = PropertyService.getProperty("test.mcUser");
69
			password = PropertyService.getProperty("test.mcPassword");
70
		} catch (PropertyNotFoundException pnfe) {
71
			System.err.println("Could not get property in static block: "
72
					+ pnfe.getMessage());
73
		}
74
	}
75

    
76
	private static String testFileLocation = null;
77
	private static String serverSchemaLocation = null;
78
	private static String badSchemaLocationXMLFile = "bad-schema-location.xml";
79
	private static String nonConformingXMLFile = "non-conforming-xml.xml";
80
	private static String goodSchemaXMLFile = "good-schema.xml";
81
	private static String goodSchemaFile1 = "chapter05ord.xsd";
82
	private static String goodSchemaFile2 = "chapter05prod.xsd";
83
	
84
	private static String getRegisteredTestSchemaSql =
85
		"SELECT * FROM xml_catalog " + 
86
		"WHERE entry_type = 'Schema' " + 
87
		"AND system_id LIKE '%chapter05%'";
88
	
89
	private static String deleteRegisteredTestSchemaSql =
90
		"DELETE FROM xml_catalog " + 
91
		"WHERE entry_type = 'Schema' " + 
92
		"AND system_id LIKE '%chapter05%'";	
93

    
94
	private Metacat m;
95

    
96
	/**
97
	 * Constructor to build the test
98
	 * 
99
	 * @param name
100
	 *            the name of the test method
101
	 */
102
	public SchemaRegistryTest(String name) {
103
		super(name);
104
	}
105

    
106
	/**
107
	 * Establish a testing framework by initializing appropriate objects
108
	 */
109
	public void setUp() {
110
		try {
111
			debug("Test Metacat: " + metacatUrl);
112
			m = MetacatFactory.createMetacatConnection(metacatUrl);
113
		} catch (MetacatInaccessibleException mie) {
114
			System.err.println("Metacat is: " + metacatUrl);
115
			fail("Metacat connection failed." + mie.getMessage());
116
		}
117
		
118
		testFileLocation = "test/clienttestfiles/";
119
		serverSchemaLocation = metacatDeployDir + "/schema/";
120
		
121
	}
122

    
123
	/**
124
	 * Release any objects after tests are complete
125
	 */
126
	public void tearDown() {
127
	}
128

    
129
	/**
130
	 * Create a suite of tests to be run together
131
	 */
132
	public static Test suite() {
133
		TestSuite suite = new TestSuite();
134
		suite.addTest(new SchemaRegistryTest("initialize"));
135
		// Test basic functions
136
		suite.addTest(new SchemaRegistryTest("newGoodSchemaRegisterTest"));
137
		suite.addTest(new SchemaRegistryTest("existingSchemaRegisterTest"));
138
		suite.addTest(new SchemaRegistryTest("newNonexistantSchemaLocationRegisterTest"));
139
		suite.addTest(new SchemaRegistryTest("newGoodSchemaBadXmlRegisterTest"));
140
		suite.addTest(new SchemaRegistryTest("existingGoodSchemaBadXmlRegisterTest"));
141
		suite.addTest(new SchemaRegistryTest("schemaInDbNotOnFileSystemTest"));
142

    
143
		return suite;
144
	}
145

    
146
	/**
147
	 * Run an initial test that always passes to check that the test harness is
148
	 * working.
149
	 */
150
	public void initialize() {
151
		assertTrue(1 == 1);
152
	}
153

    
154
	/**
155
	 * Tests adding a document that has a new valid schema and the xml conforms to the 
156
	 * schema. The file we use has two schemas, so we expect to see two rows in the 
157
	 * xml_catalog table and two schema files added to the server.
158
	 */
159
	public void newGoodSchemaRegisterTest() {
160
		try {
161
			debug("\nRunning: newGoodSchemaRegisterTest");
162

    
163
			String newdocid = generateDocid();
164
			
165
			debug("Refreshing the XMLSchemaService");
166
			httpPost(metacatUrl + "?action=refreshServices",
167
					new HashMap<String, String>());
168

    
169
			String testDocument = getTestDocument(testFileLocation + goodSchemaXMLFile);
170
			
171
			// login
172
			debug("logging in as: username=" + username + " password=" + password);
173
			m.login(username, password);
174
			
175
			// insert document.  We expect to succeed.
176
			insertDocid(newdocid + ".1", testDocument, SUCCESS, false);
177
			
178
			debug("Checking db for registered schemas");
179
			Vector<Hashtable<String,Object>> sqlResults = 
180
				dbSelect(getRegisteredTestSchemaSql, 
181
						"SchemaRegistryTest.newGoodSchemaRegisterTest");
182
			if (sqlResults.size() != 2) {
183
				fail("Expected number of test schemas in the database is 2." +
184
						" The number found was: " + sqlResults.size());
185
			}
186
			
187
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
188
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) < 
189
					FileUtil.EXISTS_READABLE) {
190
				fail("Could not find expected schema file on server: " + 
191
						serverSchemaLocation + goodSchemaFile1);
192
			}
193

    
194
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
195
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) < 
196
					FileUtil.EXISTS_READABLE) {
197
				fail("Could not find expected schema file on server: " + 
198
						serverSchemaLocation + goodSchemaFile2);
199
			}
200
			
201
			// Clean the system up
202
			debug("Deleting test schemas from db");
203
			dbUpdate(deleteRegisteredTestSchemaSql,
204
					"SchemaRegistryTest.newGoodSchemaRegisterTest");
205
			
206
			debug("Deleting test schema files from server file system");
207
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
208
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
209
			
210
			debug("Refreshing the XMLSchemaService");
211
			httpPost(metacatUrl + "?action=refreshServices",
212
					new HashMap<String, String>());
213
			
214
			deleteDocid(newdocid + ".1", SUCCESS, false);
215
			
216
			m.logout();
217

    
218
		} catch (MetacatAuthException mae) {
219
			fail("Authorization failed: " + mae.getMessage());
220
		} catch (MetacatInaccessibleException mie) {
221
			fail("Metacat Inaccessible: " + mie.getMessage());
222
		} catch (IOException ioe) {
223
			fail("I/O Exception: " + ioe.getMessage());
224
		} catch (SQLException sqle) {
225
			fail("SQL Exception: " + sqle.getMessage());
226
		} catch (Exception e) {
227
			fail("General exception: " + e.getMessage());
228
		}
229
	}
230
	
231
	/**
232
	 * Tests adding a second document that has an existing valid schema and the xml 
233
	 * conforms to the schema.  Primarily, we want to make sure that the original
234
	 * two schema entries in the database are the only two and that duplicates did
235
	 * not get entered.
236
	 */
237
	public void existingSchemaRegisterTest() {
238
		try {
239
			debug("\nRunning: existingSchemaRegisterTest");
240

    
241
			String newdocid1 = generateDocid();
242
			
243
			debug("Refreshing the XMLSchemaService");
244
			httpPost(metacatUrl + "?action=refreshServices",
245
					new HashMap<String, String>());
246

    
247
			String testDocument = getTestDocument(testFileLocation + goodSchemaXMLFile);
248
			
249
			// login
250
			debug("logging in as: username=" + username + " password=" + password);
251
			m.login(username, password);
252
			
253
			// insert document.  We expect to succeed.
254
			insertDocid(newdocid1 + ".1", testDocument, SUCCESS, false);
255
			
256
			// create a second doc id and insert another document
257
			String newdocid2 = generateDocid();
258
			insertDocid(newdocid2 + ".1", testDocument, SUCCESS, false);
259
			
260
			// Check the db for registered schemas.  We should find two and only
261
			// two.
262
			debug("Checking db for registered schemas");
263
			Vector<Hashtable<String,Object>> sqlResults = 
264
				dbSelect(getRegisteredTestSchemaSql, 
265
						"SchemaRegistryTest.existingSchemaRegisterTest");
266
			if (sqlResults.size() != 2) {
267
				fail("Expected number of test schemas in the database is 2." +
268
						" The number found was: " + sqlResults.size());
269
			}
270
			
271
			// Clean the system up
272
			debug("Deleting test schemas from db");
273
			dbUpdate(deleteRegisteredTestSchemaSql,
274
					"SchemaRegistryTest.existingSchemaRegisterTest");
275
			
276
			debug("Deleting test schema files from server file system");
277
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
278
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
279
			
280
			debug("Refreshing the XMLSchemaService");
281
			httpPost(metacatUrl + "?action=refreshServices",
282
					new HashMap<String, String>());
283
			
284
			deleteDocid(newdocid1 + ".1", SUCCESS, false);
285
			deleteDocid(newdocid2 + ".1", SUCCESS, false);
286
			
287
			m.logout();		
288
			
289
		} catch (MetacatAuthException mae) {
290
			fail("Authorization failed: " + mae.getMessage());
291
		} catch (MetacatInaccessibleException mie) {
292
			fail("Metacat Inaccessible: " + mie.getMessage());
293
		} catch (IOException ioe) {
294
			fail("I/O Exception: " + ioe.getMessage());
295
		} catch (SQLException sqle) {
296
			fail("SQL Exception: " + sqle.getMessage());
297
		} catch (Exception e) {
298
			fail("General exception: " + e.getMessage());
299
		}
300
	}
301
	
302
	/**
303
	 * Tests adding a document that has an invalid schema location. The insert
304
	 * should fail and the schema should not get registered.
305
	 */
306
	public void newNonexistantSchemaLocationRegisterTest() {
307
		try {
308
			debug("\nRunning: newNonexistantSchemaLocationRegisterTest");
309

    
310
			String newdocid1 = generateDocid();
311
			
312
			debug("Refreshing the XMLSchemaService");
313
			httpPost(metacatUrl + "?action=refreshServices",
314
					new HashMap<String, String>());
315

    
316
			String testDocument = getTestDocument(testFileLocation + badSchemaLocationXMLFile);
317
			
318
			// login
319
			debug("logging in as: username=" + username + " password=" + password);
320
			m.login(username, password);
321
			
322
			// insert document.  We expect to fail with a MetacatException because the schemaLocation
323
			// does not exist.
324
			insertDocidExpectException(newdocid1 + ".1", testDocument, "Failed to read schema document");
325
			
326
			// Check the db for registered schemas.  We should find none.
327
			debug("Checking db for registered schemas");
328
			Vector<Hashtable<String,Object>> sqlResults = 
329
				dbSelect(getRegisteredTestSchemaSql, 
330
						"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
331
			if (sqlResults.size() != 0) {
332
				fail("Expected number of test schemas in the database is 0." +
333
						" The number found was: " + sqlResults.size());
334
			}
335
			
336
			
337
			// check the system for the schema files.  There should be none.
338
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
339
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) >= 
340
					FileUtil.EXISTS_ONLY) {
341
				fail("Found unexpected schema file on server: " + 
342
						serverSchemaLocation + goodSchemaFile1);
343
			}
344

    
345
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
346
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) >= 
347
					FileUtil.EXISTS_ONLY) {
348
				fail("Found unexpected schema file on server: " + 
349
						serverSchemaLocation + goodSchemaFile2);
350
			}
351
			
352
			// Clean the system up, just to be safe.
353
			debug("Deleting test schemas from db");
354
			dbUpdate(deleteRegisteredTestSchemaSql,
355
					"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
356
			
357
			debug("Deleting test schema files from server file system");
358
			try {
359
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
360
			} catch (FileNotFoundException fnfe) {
361
				// Do nothing here. We are hoping that the file didn't exist.
362
			}
363

    
364
			try {
365
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
366
			} catch (FileNotFoundException fnfe) {
367
				// Do nothing here. We are hoping that the file didn't exist.
368
			}
369

    
370
			debug("Refreshing the XMLSchemaService");
371
			httpPost(metacatUrl + "?action=refreshServices",
372
					new HashMap<String, String>());
373

    
374
			m.logout();		
375
			
376
		} catch (MetacatAuthException mae) {
377
			fail("Authorization failed: " + mae.getMessage());
378
		} catch (MetacatInaccessibleException mie) {
379
			fail("Metacat Inaccessible: " + mie.getMessage());
380
		} catch (IOException ioe) {
381
			fail("I/O Exception: " + ioe.getMessage());
382
		} catch (SQLException sqle) {
383
			fail("SQL Exception: " + sqle.getMessage());
384
		} catch (Exception e) {
385
			fail("General exception: " + e.getMessage());
386
		}
387
	}
388
	
389
	/**
390
	 * Tests adding a document that has a valid schema location which has
391
	 * already been registered in metacat, but the xml doesn't conform to the
392
	 * schema. The insert should fail.
393
	 */
394
	public void newGoodSchemaBadXmlRegisterTest() {
395
		try {
396
			debug("\nRunning: newGoodSchemaBadXmlRegisterTest");
397

    
398
			String newdocid1 = generateDocid();
399
			
400
			debug("Refreshing the XMLSchemaService");
401
			httpPost(metacatUrl + "?action=refreshServices",
402
					new HashMap<String, String>());
403

    
404
			String testDocument = getTestDocument(testFileLocation + nonConformingXMLFile);
405
			
406
			// login
407
			debug("logging in as: username=" + username + " password=" + password);
408
			m.login(username, password);
409
			
410
			// insert document.  We expect to fail with a MetacatException because the schemaLocation
411
			// does not exist.
412
			insertDocidExpectException(newdocid1 + ".1", testDocument, "is not allowed to appear in element");
413
			
414
			// Check the db for registered schemas.  We should find none.
415
			debug("Checking db for registered schemas");
416
			Vector<Hashtable<String,Object>> sqlResults = 
417
				dbSelect(getRegisteredTestSchemaSql, 
418
						"SchemaRegistryTest.newGoodSchemaBadXmlRegisterTest");
419
			if (sqlResults.size() != 0) {
420
				fail("Expected number of test schemas in the database is 0." +
421
						" The number found was: " + sqlResults.size());
422
			}		
423
			
424
			// check the system for the schema files.  There should be none.
425
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
426
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) >= 
427
					FileUtil.EXISTS_ONLY) {
428
				fail("Found unexpected schema file on server: " + 
429
						serverSchemaLocation + goodSchemaFile1);
430
			}
431

    
432
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
433
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) >= 
434
					FileUtil.EXISTS_ONLY) {
435
				fail("Found unexpected schema file on server: " + 
436
						serverSchemaLocation + goodSchemaFile2);
437
			}
438
			
439
			// Clean the system up, just to be safe.
440
			debug("Deleting test schemas from db");
441
			dbUpdate(deleteRegisteredTestSchemaSql,
442
					"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
443
			
444
			debug("Deleting test schema files from server file system");
445
			try {
446
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
447
			} catch (FileNotFoundException fnfe) {
448
				// Do nothing here. We are hoping that the file didn't exist.
449
			}
450

    
451
			try {
452
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
453
			} catch (FileNotFoundException fnfe) {
454
				// Do nothing here. We are hoping that the file didn't exist.
455
			}
456

    
457
			debug("Refreshing the XMLSchemaService");
458
			httpPost(metacatUrl + "?action=refreshServices",
459
					new HashMap<String, String>());
460

    
461
			m.logout();		
462
			
463
		} catch (MetacatAuthException mae) {
464
				fail("Authorization failed: " + mae.getMessage());
465
		} catch (MetacatInaccessibleException mie) {
466
			fail("Metacat Inaccessible: " + mie.getMessage());
467
		} catch (IOException ioe) {
468
			fail("I/O Exception: " + ioe.getMessage());
469
		} catch (SQLException sqle) {
470
			fail("SQL Exception: " + sqle.getMessage());
471
		} catch (Exception e) {
472
			fail("General exception: " + e.getMessage());
473
		}
474
	}
475
	
476
	/**
477
	 * Tests adding a document that has a valid schema location, but the xml
478
	 * doesn't conform to the schema. The insert should fail and the schema
479
	 * should not get registered.
480
	 */
481
	public void existingGoodSchemaBadXmlRegisterTest() {
482
		try {
483
			debug("\nRunning: existingGoodSchemaBadXmlRegisterTest");
484
		
485
			debug("Refreshing the XMLSchemaService");
486
			httpPost(metacatUrl + "?action=refreshServices",
487
					new HashMap<String, String>());
488

    
489
			// login
490
			debug("logging in as: username=" + username + " password=" + password);
491
			m.login(username, password);
492
			
493
			// insert good document.  We expect to succeed.
494
			String newdocid1 = generateDocid();
495
			String testDocument1 = getTestDocument(testFileLocation + goodSchemaXMLFile);
496
			insertDocid(newdocid1 + ".1", testDocument1, SUCCESS, false);
497

    
498
			String newdocid2 = generateDocid();
499
			String testDocument2 = getTestDocument(testFileLocation + nonConformingXMLFile);
500
			// attempt to insert non-conforming document.  We expect to fail with a MetacatException 
501
			// because the xml does not conform to the schema
502
			insertDocidExpectException(newdocid2 + ".1", testDocument2, "is not allowed to appear in element");
503
			
504
			// Check the db for registered schemas.  We should find none.
505
			debug("Checking db for registered schemas");
506
			Vector<Hashtable<String,Object>> sqlResults = 
507
				dbSelect(getRegisteredTestSchemaSql, 
508
						"SchemaRegistryTest.existingGoodSchemaBadXmlRegisterTest");
509
			if (sqlResults.size() != 2) {
510
				fail("Expected number of test schemas in the database is 2." +
511
						" The number found was: " + sqlResults.size());
512
			}		
513
			
514
			// Clean the system up.
515
			debug("Deleting test schemas from db");
516
			dbUpdate(deleteRegisteredTestSchemaSql,
517
					"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
518
			
519
			debug("Deleting test schema files from server file system");
520
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
521
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
522

    
523
			debug("Refreshing the XMLSchemaService");
524
			httpPost(metacatUrl + "?action=refreshServices",
525
					new HashMap<String, String>());
526
			
527
			deleteDocid(newdocid1 + ".1", SUCCESS, false);
528

    
529
			m.logout();		
530
			
531
		} catch (MetacatAuthException mae) {
532
			fail("Authorization failed: " + mae.getMessage());
533
		} catch (MetacatInaccessibleException mie) {
534
			fail("Metacat Inaccessible: " + mie.getMessage());
535
		} catch (IOException ioe) {
536
			fail("I/O Exception: " + ioe.getMessage());
537
		} catch (SQLException sqle) {
538
			fail("SQL Exception: " + sqle.getMessage());
539
		} catch (Exception e) {
540
			fail("General exception: " + e.getMessage());
541
		}
542
	}
543
	
544
	/**
545
	 * Tests adding a second document that has an existing valid schema and the
546
	 * xml conforms to the schema. Primarily, we want to make sure that the
547
	 * original two schema entries in the database are the only two and that
548
	 * duplicates did not get entered.
549
	 */
550
	public void schemaInDbNotOnFileSystemTest() {
551
		try {
552
			debug("\nRunning: schemaInDbNotOnFileSystemTest");
553
			
554
			debug("Refreshing the XMLSchemaService");
555
			httpPost(metacatUrl + "?action=refreshServices",
556
					new HashMap<String, String>());
557
			
558
			// login
559
			debug("logging in as: username=" + username + " password=" + password);
560
			m.login(username, password);
561
			
562
			// insert document.  We expect to succeed.			
563
			String newdocid1 = generateDocid();
564
			String testDocument = getTestDocument(testFileLocation + goodSchemaXMLFile);
565
			insertDocid(newdocid1 + ".1", testDocument, SUCCESS, false);
566
			
567
			debug("Deleting test schema files from server file system");
568
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
569
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
570
			
571
			debug("Refreshing the XMLSchemaService");
572
			httpPost(metacatUrl + "?action=refreshServices",
573
					new HashMap<String, String>());
574
			
575
			// create a second doc id and insert another document
576
			String newdocid2 = generateDocid();
577
			insertDocid(newdocid2 + ".1", testDocument, SUCCESS, false);
578
			
579
			// Check the db for registered schemas.  We should find two and only
580
			// two.
581
			debug("Checking db for registered schemas");
582
			Vector<Hashtable<String,Object>> sqlResults = 
583
				dbSelect(getRegisteredTestSchemaSql, 
584
						"SchemaRegistryTest.schemaInDbNotOnFileSystemTest");
585
			if (sqlResults.size() != 2) {
586
				fail("Expected number of test schemas in the database is 2." +
587
						" The number found was: " + sqlResults.size());
588
			}
589
			
590
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
591
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) < 
592
					FileUtil.EXISTS_READABLE) {
593
				fail("Could not find expected schema file on server: " + 
594
						serverSchemaLocation + goodSchemaFile1);
595
			}
596

    
597
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
598
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) < 
599
					FileUtil.EXISTS_READABLE) {
600
				fail("Could not find expected schema file on server: " + 
601
						serverSchemaLocation + goodSchemaFile2);
602
			}
603
			
604
			// Clean the system up
605
			debug("Deleting test schemas from db");
606
			dbUpdate(deleteRegisteredTestSchemaSql,
607
					"SchemaRegistryTest.schemaInDbNotOnFileSystemTest");
608
			
609
			debug("Deleting test schema files from server file system");
610
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
611
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
612
			
613
			debug("Refreshing the XMLSchemaService");
614
			httpPost(metacatUrl + "?action=refreshServices",
615
					new HashMap<String, String>());
616
			
617
			deleteDocid(newdocid1 + ".1", SUCCESS, false);
618
			deleteDocid(newdocid2 + ".1", SUCCESS, false);
619
			
620
			m.logout();		
621
			
622
		} catch (MetacatAuthException mae) {
623
			fail("Authorization failed: " + mae.getMessage());
624
		} catch (MetacatInaccessibleException mie) {
625
			fail("Metacat Inaccessible: " + mie.getMessage());
626
		} catch (IOException ioe) {
627
			fail("I/O Exception: " + ioe.getMessage());
628
		} catch (SQLException sqle) {
629
			fail("SQL Exception: " + sqle.getMessage());
630
		} catch (Exception e) {
631
			fail("General exception: " + e.getMessage());
632
		}
633
	}
634
	
635
	/**
636
	 * @param documentLocation
637
	 *            the path of the document to read.
638
	 * @return a string holding the contents of the document with the contextUrl
639
	 *         token replaced by the test.contextUrl property
640
	 */
641
	private String getTestDocument(String documentLocation) throws IOException,
642
			PropertyNotFoundException {
643
		String testDocument = null;
644
		try {
645
			testDocument = FileUtil.readFileToString(documentLocation);
646
		} catch (UtilException ue) {
647
			throw new IOException("Error reading file to string: " +  ue.getMessage());
648
		}
649

    
650
		String contextUrl = PropertyService.getProperty("test.contextUrl");
651
		testDocument = testDocument.replaceAll("@contextUrl@", contextUrl);
652

    
653
		return testDocument;
654
	}
655
	
656
	/**
657
	 * Insert a document into metacat via the metacat client.
658
	 * 
659
	 * @param docid
660
	 *            the id of the document to insert
661
	 * @param testdocument
662
	 *            the contents of the document
663
	 * @param result
664
	 *            do we expect this to succed or fail
665
	 * @param expectKarmaException
666
	 *            do we expect it to fail with a KarmaException
667
	 * @return the response that was passed back from metacat
668
	 */
669
	private String insertDocid(String docid, String testdocument, boolean result,
670
			boolean expectKarmaException) {
671
		debug("insertDocid(): docid=" + docid + " expectedResult=" + result
672
				+ " expectKarmaException=" + expectKarmaException);
673
		String response = null;
674
		try {
675
			response = m.insert(docid, new StringReader(testdocument), null);
676
			debug("expected result: " + result);
677
			if (result) {
678
				assertTrue(response, (response.indexOf("<success>") != -1));
679
				assertTrue(response, response.indexOf(docid) != -1);
680
			} else {
681
				debug("in else, checking: " + (response.indexOf("<success>") == -1));
682
				assertTrue(response, (response.indexOf("<success>") == -1));
683
			}
684
			debug("insertDocid():  response=" + response);
685
		} catch (MetacatInaccessibleException mie) {
686
			fail("Metacat Inaccessible:\n" + mie.getMessage());
687
		} catch (InsufficientKarmaException ike) {
688
			if (!expectKarmaException) {
689
				fail("Insufficient karma:\n" + ike.getMessage());
690
			}
691
		} catch (MetacatException me) {
692
			fail("Metacat Error:\n" + me.getMessage());
693
		} catch (Exception e) {
694
			fail("General exception:\n" + e.getMessage());
695
		}
696
		return response;
697
	}
698
	
699
	/**
700
	 * Try to insert a document into metacat. This is used when we expect a
701
	 * MetacatException
702
	 * 
703
	 * @param docid
704
	 *            the document id we are going to attempt to insert
705
	 * @param testdocument
706
	 *            the contents of the document we are going to attempt to insert
707
	 * @param expectedException
708
	 *            text that should be a substring of the MetacatException
709
	 *            message
710
	 */
711
	private void insertDocidExpectException(String docid, String testdocument, String expectedException) {
712
		debug("insertDocidExpectException(): docid=" + docid + " expectedException=" + expectedException);
713

    
714
		String response = null;
715
		try {
716
			response = m.insert(docid, new StringReader(testdocument), null);	
717
			fail("Expecting a MetacatException.  Instead, got response: " + response);
718
		} catch (MetacatInaccessibleException mie) {
719
			fail("Metacat Inaccessible:\n" + mie.getMessage());
720
		} catch (InsufficientKarmaException ike) {
721
			fail("Insufficient karma:\n" + ike.getMessage());
722
		} catch (MetacatException me) {
723
			assertTrue(me.getMessage(), me.getMessage().contains(expectedException));
724
		} catch (Exception e) {
725
			fail("General exception:\n" + e.getMessage());
726
		}
727
		
728
		
729
	}
730

    
731
	/**
732
	 * Delete a document into metacat. The expected result is passed as result
733
	 */
734
	private void deleteDocid(String docid, boolean result, boolean expectedKarmaFailure) {
735
		debug("deleteDocid(): docid=" + docid + " expectedResult=" + result
736
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
737
		try {
738
			Thread.sleep(5000);
739
			String response = m.delete(docid);
740
			if (result) {
741
				assertTrue(response, response.indexOf("<success>") != -1);
742
			} else {
743
				assertTrue(response, response.indexOf("<success>") == -1);
744
			}
745
			debug("deleteDocid():  response=" + response);
746
		} catch (MetacatInaccessibleException mie) {
747
			fail("Metacat Inaccessible:\n" + mie.getMessage());
748
		} catch (InsufficientKarmaException ike) {
749
			if (!expectedKarmaFailure) {
750
				fail("Insufficient karma:\n" + ike.getMessage());
751
			}
752
		} catch (MetacatException me) {
753
			if (result) {
754
				fail("Metacat Error:\n" + me.getMessage());
755
			} else {
756
				debug("Metacat Error:\n" + me.getMessage());
757
			}
758
		} catch (Exception e) {
759
			fail("General exception:\n" + e.getMessage());
760
		}
761
	}
762

    
763
	/**
764
	 * Create a hopefully unique docid for testing insert and update. Does not
765
	 * include the 'revision' part of the id.
766
	 * 
767
	 * @return a String docid based on the current date and time
768
	 */
769
	private String generateDocid() {
770
		try {
771
			Thread.sleep(1100);
772
		} catch (Exception e) {
773
			debug("Could not sleep: " + e.getMessage());
774
		}
775
		StringBuffer docid = new StringBuffer("test");
776
		docid.append(".");
777

    
778
		// Create a calendar to get the date formatted properly
779
		String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
780
		SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
781
		pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
782
		pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
783
		Calendar calendar = new GregorianCalendar(pdt);
784
		Date trialTime = new Date();
785
		calendar.setTime(trialTime);
786
		docid.append(calendar.get(Calendar.YEAR));
787
		docid.append(calendar.get(Calendar.DAY_OF_YEAR));
788
		docid.append(calendar.get(Calendar.HOUR_OF_DAY));
789
		docid.append(calendar.get(Calendar.MINUTE));
790
		docid.append(calendar.get(Calendar.SECOND));
791

    
792
		return docid.toString();
793
	}
794
	
795
}
(18-18/22)