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
	private static String includedSchemaXMLFile = "company.xml";
84
	private static String includedSchemaFile1="company.xsd";
85
	private static String includedSchemaFile2="worker.xsd";
86
	private static String includedSchemaFile3="item.xsd";
87
	private static String includedSchemaFile4="product.xsd";
88
	
89
	
90
	private static String getRegisteredTestSchemaSql =
91
		"SELECT * FROM xml_catalog " + 
92
		"WHERE entry_type = 'Schema' " + 
93
		"AND system_id LIKE '%chapter05%'";
94
	
95
	private static String deleteRegisteredTestSchemaSql =
96
		"DELETE FROM xml_catalog " + 
97
		"WHERE entry_type = 'Schema' " + 
98
		"AND system_id LIKE '%chapter05%'";	
99
	
100
	private static String getRegisteredIncludedTestSchemaSql =
101
    "SELECT * FROM xml_catalog " + 
102
    "WHERE entry_type = 'Schema' " + 
103
    "AND system_id LIKE '%company%'";
104
  
105
  private static String deleteRegisteredIncludedTestSchemaSql =
106
    "DELETE FROM xml_catalog " + 
107
    "WHERE entry_type = 'Schema' " + 
108
    "AND system_id LIKE '%company%'"; 
109

    
110
	private Metacat m;
111

    
112
	/**
113
	 * Constructor to build the test
114
	 * 
115
	 * @param name
116
	 *            the name of the test method
117
	 */
118
	public SchemaRegistryTest(String name) {
119
		super(name);
120
	}
121

    
122
	/**
123
	 * Establish a testing framework by initializing appropriate objects
124
	 */
125
	public void setUp() {
126
		try {
127
			debug("Test Metacat: " + metacatUrl);
128
			m = MetacatFactory.createMetacatConnection(metacatUrl);
129
		} catch (MetacatInaccessibleException mie) {
130
			System.err.println("Metacat is: " + metacatUrl);
131
			fail("Metacat connection failed." + mie.getMessage());
132
		}
133
		
134
		testFileLocation = "test/clienttestfiles/";
135
		serverSchemaLocation = metacatDeployDir + "/schema/";
136
		
137
	}
138

    
139
	/**
140
	 * Release any objects after tests are complete
141
	 */
142
	public void tearDown() {
143
	}
144

    
145
	/**
146
	 * Create a suite of tests to be run together
147
	 */
148
	public static Test suite() {
149
		TestSuite suite = new TestSuite();
150
		suite.addTest(new SchemaRegistryTest("initialize"));
151
		// Test basic functions
152
		suite.addTest(new SchemaRegistryTest("newGoodSchemaRegisterTest"));
153
		suite.addTest(new SchemaRegistryTest("existingSchemaRegisterTest"));
154
		suite.addTest(new SchemaRegistryTest("newNonexistantSchemaLocationRegisterTest"));
155
		suite.addTest(new SchemaRegistryTest("newGoodSchemaBadXmlRegisterTest"));
156
		suite.addTest(new SchemaRegistryTest("existingGoodSchemaBadXmlRegisterTest"));
157
		suite.addTest(new SchemaRegistryTest("schemaInDbNotOnFileSystemTest"));
158
		suite.addTest(new SchemaRegistryTest("includedSchemaRegisterTest"));
159
		return suite;
160
	}
161

    
162
	/**
163
	 * Run an initial test that always passes to check that the test harness is
164
	 * working.
165
	 */
166
	public void initialize() {
167
		assertTrue(1 == 1);
168
	}
169

    
170
	/**
171
	 * Tests adding a document that has a new valid schema and the xml conforms to the 
172
	 * schema. The file we use has two schemas, so we expect to see two rows in the 
173
	 * xml_catalog table and two schema files added to the server.
174
	 */
175
	public void newGoodSchemaRegisterTest() {
176
		try {
177
			debug("\nRunning: newGoodSchemaRegisterTest");
178

    
179
			String newdocid = generateDocid();
180
			
181
			debug("Refreshing the XMLSchemaService");
182
			httpPost(metacatUrl + "?action=refreshServices",
183
					new HashMap<String, String>());
184

    
185
			String testDocument = getTestDocument(testFileLocation + goodSchemaXMLFile);
186
			
187
			// login
188
			debug("logging in as: username=" + username + " password=" + password);
189
			m.login(username, password);
190
			
191
			// insert document.  We expect to succeed.
192
			insertDocid(newdocid + ".1", testDocument, SUCCESS, false);
193
			
194
			debug("Checking db for registered schemas");
195
			Vector<Hashtable<String,Object>> sqlResults = 
196
				dbSelect(getRegisteredTestSchemaSql, 
197
						"SchemaRegistryTest.newGoodSchemaRegisterTest");
198
			if (sqlResults.size() != 2) {
199
				fail("Expected number of test schemas in the database is 2." +
200
						" The number found was: " + sqlResults.size());
201
			}
202
			
203
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
204
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) < 
205
					FileUtil.EXISTS_READABLE) {
206
				fail("Could not find expected schema file on server: " + 
207
						serverSchemaLocation + goodSchemaFile1);
208
			}
209

    
210
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
211
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) < 
212
					FileUtil.EXISTS_READABLE) {
213
				fail("Could not find expected schema file on server: " + 
214
						serverSchemaLocation + goodSchemaFile2);
215
			}
216
			
217
			// Clean the system up
218
			debug("Deleting test schemas from db");
219
			dbUpdate(deleteRegisteredTestSchemaSql,
220
					"SchemaRegistryTest.newGoodSchemaRegisterTest");
221
			
222
			debug("Deleting test schema files from server file system");
223
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
224
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
225
			
226
			debug("Refreshing the XMLSchemaService");
227
			httpPost(metacatUrl + "?action=refreshServices",
228
					new HashMap<String, String>());
229
			
230
			deleteDocid(newdocid + ".1", SUCCESS, false);
231
			
232
			m.logout();
233

    
234
		} catch (MetacatAuthException mae) {
235
			fail("Authorization failed: " + mae.getMessage());
236
		} catch (MetacatInaccessibleException mie) {
237
			fail("Metacat Inaccessible: " + mie.getMessage());
238
		} catch (IOException ioe) {
239
			fail("I/O Exception: " + ioe.getMessage());
240
		} catch (SQLException sqle) {
241
			fail("SQL Exception: " + sqle.getMessage());
242
		} catch (Exception e) {
243
			fail("General exception: " + e.getMessage());
244
		}
245
	}
246
	
247
	/**
248
	 * Tests adding a second document that has an existing valid schema and the xml 
249
	 * conforms to the schema.  Primarily, we want to make sure that the original
250
	 * two schema entries in the database are the only two and that duplicates did
251
	 * not get entered.
252
	 */
253
	public void existingSchemaRegisterTest() {
254
		try {
255
			debug("\nRunning: existingSchemaRegisterTest");
256

    
257
			String newdocid1 = generateDocid();
258
			
259
			debug("Refreshing the XMLSchemaService");
260
			httpPost(metacatUrl + "?action=refreshServices",
261
					new HashMap<String, String>());
262

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

    
326
			String newdocid1 = generateDocid();
327
			
328
			debug("Refreshing the XMLSchemaService");
329
			httpPost(metacatUrl + "?action=refreshServices",
330
					new HashMap<String, String>());
331

    
332
			String testDocument = getTestDocument(testFileLocation + badSchemaLocationXMLFile);
333
			
334
			// login
335
			debug("logging in as: username=" + username + " password=" + password);
336
			m.login(username, password);
337
			
338
			// insert document.  We expect to fail with a MetacatException because the schemaLocation
339
			// does not exist.
340
			insertDocidExpectException(newdocid1 + ".1", testDocument, "Failed to read schema document");
341
			
342
			// Check the db for registered schemas.  We should find none.
343
			debug("Checking db for registered schemas");
344
			Vector<Hashtable<String,Object>> sqlResults = 
345
				dbSelect(getRegisteredTestSchemaSql, 
346
						"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
347
			if (sqlResults.size() != 0) {
348
				fail("Expected number of test schemas in the database is 0." +
349
						" The number found was: " + sqlResults.size());
350
			}
351
			
352
			
353
			// check the system for the schema files.  There should be none.
354
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
355
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) >= 
356
					FileUtil.EXISTS_ONLY) {
357
				fail("Found unexpected schema file on server: " + 
358
						serverSchemaLocation + goodSchemaFile1);
359
			}
360

    
361
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
362
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) >= 
363
					FileUtil.EXISTS_ONLY) {
364
				fail("Found unexpected schema file on server: " + 
365
						serverSchemaLocation + goodSchemaFile2);
366
			}
367
			
368
			// Clean the system up, just to be safe.
369
			debug("Deleting test schemas from db");
370
			dbUpdate(deleteRegisteredTestSchemaSql,
371
					"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
372
			
373
			debug("Deleting test schema files from server file system");
374
			try {
375
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
376
			} catch (FileNotFoundException fnfe) {
377
				// Do nothing here. We are hoping that the file didn't exist.
378
			}
379

    
380
			try {
381
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
382
			} catch (FileNotFoundException fnfe) {
383
				// Do nothing here. We are hoping that the file didn't exist.
384
			}
385

    
386
			debug("Refreshing the XMLSchemaService");
387
			httpPost(metacatUrl + "?action=refreshServices",
388
					new HashMap<String, String>());
389

    
390
			m.logout();		
391
			
392
		} catch (MetacatAuthException mae) {
393
			fail("Authorization failed: " + mae.getMessage());
394
		} catch (MetacatInaccessibleException mie) {
395
			fail("Metacat Inaccessible: " + mie.getMessage());
396
		} catch (IOException ioe) {
397
			fail("I/O Exception: " + ioe.getMessage());
398
		} catch (SQLException sqle) {
399
			fail("SQL Exception: " + sqle.getMessage());
400
		} catch (Exception e) {
401
			fail("General exception: " + e.getMessage());
402
		}
403
	}
404
	
405
	/**
406
	 * Tests adding a document that has a valid schema location which has
407
	 * already been registered in metacat, but the xml doesn't conform to the
408
	 * schema. The insert should fail.
409
	 */
410
	public void newGoodSchemaBadXmlRegisterTest() {
411
		try {
412
			debug("\nRunning: newGoodSchemaBadXmlRegisterTest");
413

    
414
			String newdocid1 = generateDocid();
415
			
416
			debug("Refreshing the XMLSchemaService");
417
			httpPost(metacatUrl + "?action=refreshServices",
418
					new HashMap<String, String>());
419

    
420
			String testDocument = getTestDocument(testFileLocation + nonConformingXMLFile);
421
			
422
			// login
423
			debug("logging in as: username=" + username + " password=" + password);
424
			m.login(username, password);
425
			
426
			// insert document.  We expect to fail with a MetacatException because the schemaLocation
427
			// does not exist.
428
			insertDocidExpectException(newdocid1 + ".1", testDocument, "is not allowed to appear in element");
429
			
430
			// Check the db for registered schemas.  We should find none.
431
			debug("Checking db for registered schemas");
432
			Vector<Hashtable<String,Object>> sqlResults = 
433
				dbSelect(getRegisteredTestSchemaSql, 
434
						"SchemaRegistryTest.newGoodSchemaBadXmlRegisterTest");
435
			if (sqlResults.size() != 0) {
436
				fail("Expected number of test schemas in the database is 0." +
437
						" The number found was: " + sqlResults.size());
438
			}		
439
			
440
			// check the system for the schema files.  There should be none.
441
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
442
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) >= 
443
					FileUtil.EXISTS_ONLY) {
444
				fail("Found unexpected schema file on server: " + 
445
						serverSchemaLocation + goodSchemaFile1);
446
			}
447

    
448
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
449
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) >= 
450
					FileUtil.EXISTS_ONLY) {
451
				fail("Found unexpected schema file on server: " + 
452
						serverSchemaLocation + goodSchemaFile2);
453
			}
454
			
455
			// Clean the system up, just to be safe.
456
			debug("Deleting test schemas from db");
457
			dbUpdate(deleteRegisteredTestSchemaSql,
458
					"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
459
			
460
			debug("Deleting test schema files from server file system");
461
			try {
462
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
463
			} catch (FileNotFoundException fnfe) {
464
				// Do nothing here. We are hoping that the file didn't exist.
465
			}
466

    
467
			try {
468
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
469
			} catch (FileNotFoundException fnfe) {
470
				// Do nothing here. We are hoping that the file didn't exist.
471
			}
472

    
473
			debug("Refreshing the XMLSchemaService");
474
			httpPost(metacatUrl + "?action=refreshServices",
475
					new HashMap<String, String>());
476

    
477
			m.logout();		
478
			
479
		} catch (MetacatAuthException mae) {
480
				fail("Authorization failed: " + mae.getMessage());
481
		} catch (MetacatInaccessibleException mie) {
482
			fail("Metacat Inaccessible: " + mie.getMessage());
483
		} catch (IOException ioe) {
484
			fail("I/O Exception: " + ioe.getMessage());
485
		} catch (SQLException sqle) {
486
			fail("SQL Exception: " + sqle.getMessage());
487
		} catch (Exception e) {
488
			fail("General exception: " + e.getMessage());
489
		}
490
	}
491
	
492
	/**
493
	 * Tests adding a document that has a valid schema location, but the xml
494
	 * doesn't conform to the schema. The insert should fail and the schema
495
	 * should not get registered.
496
	 */
497
	public void existingGoodSchemaBadXmlRegisterTest() {
498
		try {
499
			debug("\nRunning: existingGoodSchemaBadXmlRegisterTest");
500
		
501
			debug("Refreshing the XMLSchemaService");
502
			httpPost(metacatUrl + "?action=refreshServices",
503
					new HashMap<String, String>());
504

    
505
			// login
506
			debug("logging in as: username=" + username + " password=" + password);
507
			m.login(username, password);
508
			
509
			// insert good document.  We expect to succeed.
510
			String newdocid1 = generateDocid();
511
			String testDocument1 = getTestDocument(testFileLocation + goodSchemaXMLFile);
512
			insertDocid(newdocid1 + ".1", testDocument1, SUCCESS, false);
513

    
514
			String newdocid2 = generateDocid();
515
			String testDocument2 = getTestDocument(testFileLocation + nonConformingXMLFile);
516
			// attempt to insert non-conforming document.  We expect to fail with a MetacatException 
517
			// because the xml does not conform to the schema
518
			insertDocidExpectException(newdocid2 + ".1", testDocument2, "is not allowed to appear in element");
519
			
520
			// Check the db for registered schemas.  We should find none.
521
			debug("Checking db for registered schemas");
522
			Vector<Hashtable<String,Object>> sqlResults = 
523
				dbSelect(getRegisteredTestSchemaSql, 
524
						"SchemaRegistryTest.existingGoodSchemaBadXmlRegisterTest");
525
			if (sqlResults.size() != 2) {
526
				fail("Expected number of test schemas in the database is 2." +
527
						" The number found was: " + sqlResults.size());
528
			}		
529
			
530
			// Clean the system up.
531
			debug("Deleting test schemas from db");
532
			dbUpdate(deleteRegisteredTestSchemaSql,
533
					"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
534
			
535
			debug("Deleting test schema files from server file system");
536
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
537
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
538

    
539
			debug("Refreshing the XMLSchemaService");
540
			httpPost(metacatUrl + "?action=refreshServices",
541
					new HashMap<String, String>());
542
			
543
			deleteDocid(newdocid1 + ".1", SUCCESS, false);
544

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

    
613
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile2);			
614
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile2) < 
615
					FileUtil.EXISTS_READABLE) {
616
				fail("Could not find expected schema file on server: " + 
617
						serverSchemaLocation + goodSchemaFile2);
618
			}
619
			
620
			// Clean the system up
621
			debug("Deleting test schemas from db");
622
			dbUpdate(deleteRegisteredTestSchemaSql,
623
					"SchemaRegistryTest.schemaInDbNotOnFileSystemTest");
624
			
625
			debug("Deleting test schema files from server file system");
626
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile1);
627
			FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
628
			
629
			debug("Refreshing the XMLSchemaService");
630
			httpPost(metacatUrl + "?action=refreshServices",
631
					new HashMap<String, String>());
632
			
633
			deleteDocid(newdocid1 + ".1", SUCCESS, false);
634
			deleteDocid(newdocid2 + ".1", SUCCESS, false);
635
			
636
			m.logout();		
637
			
638
		} catch (MetacatAuthException mae) {
639
			fail("Authorization failed: " + mae.getMessage());
640
		} catch (MetacatInaccessibleException mie) {
641
			fail("Metacat Inaccessible: " + mie.getMessage());
642
		} catch (IOException ioe) {
643
			fail("I/O Exception: " + ioe.getMessage());
644
		} catch (SQLException sqle) {
645
			fail("SQL Exception: " + sqle.getMessage());
646
		} catch (Exception e) {
647
			fail("General exception: " + e.getMessage());
648
		}
649
	}
650
	
651
	/**
652
   * Tests adding a document that has a new valid schema and the xml conforms to the 
653
   * schema. The schema has included schemas. We expect one entry will be added to
654
   * the db. But four schema files will be downloaded (four schemas share the same 
655
   * target namespace).
656
   */
657
  public void includedSchemaRegisterTest() {
658
    try {
659
      debug("\nRunning: newGoodSchemaRegisterTest");
660

    
661
      String newdocid = generateDocid();
662
      
663
      debug("Refreshing the XMLSchemaService");
664
      httpPost(metacatUrl + "?action=refreshServices",
665
          new HashMap<String, String>());
666

    
667
      String testDocument = getTestDocument(testFileLocation + includedSchemaXMLFile);
668
      
669
      // login
670
      debug("logging in as: username=" + username + " password=" + password);
671
      m.login(username, password);
672
      
673
      // insert document.  We expect to succeed.
674
      insertDocid(newdocid + ".1", testDocument, SUCCESS, false);
675
      
676
      debug("Checking db for registered schemas");
677
      Vector<Hashtable<String,Object>> sqlResults = 
678
        dbSelect(getRegisteredIncludedTestSchemaSql, 
679
            "SchemaRegistryTest.includedSchemaRegisterTest");
680
      if (sqlResults.size() != 1) {
681
        fail("Expected number of test schemas in the database is 1." +
682
            " The number found was: " + sqlResults.size());
683
      }
684
      deleteDocid(newdocid + ".1", SUCCESS, false);
685
      debug("Checking server for registered schema file: " + serverSchemaLocation + includedSchemaFile1);
686
      if( FileUtil.getFileStatus(serverSchemaLocation + includedSchemaFile1) < 
687
          FileUtil.EXISTS_READABLE) {
688
        fail("Could not find expected schema file on server: " + 
689
            serverSchemaLocation + includedSchemaFile1);
690
      }
691

    
692
      debug("Checking server for registered schema file: " + serverSchemaLocation + includedSchemaFile2);
693
      if( FileUtil.getFileStatus(serverSchemaLocation + includedSchemaFile2) < 
694
          FileUtil.EXISTS_READABLE) {
695
        fail("Could not find expected schema file on server: " + 
696
            serverSchemaLocation + includedSchemaFile2);
697
      }
698
      
699
      debug("Checking server for registered schema file: " + serverSchemaLocation + includedSchemaFile3);
700
      if( FileUtil.getFileStatus(serverSchemaLocation + includedSchemaFile3) < 
701
          FileUtil.EXISTS_READABLE) {
702
        fail("Could not find expected schema file on server: " + 
703
            serverSchemaLocation + includedSchemaFile3);
704
      }
705
      
706
      debug("Checking server for registered schema file: " + serverSchemaLocation + includedSchemaFile4);
707
      if( FileUtil.getFileStatus(serverSchemaLocation + includedSchemaFile4) < 
708
          FileUtil.EXISTS_READABLE) {
709
        fail("Could not find expected schema file on server: " + 
710
            serverSchemaLocation + includedSchemaFile4);
711
      }
712
      
713
      String newdocid2 = generateDocid();
714
      //insert document.  We expect to succeed.
715
      insertDocid(newdocid2 + ".1", testDocument, SUCCESS, false);
716
      String newdocid3 = generateDocid();
717
      // insert document.  We expect to succeed.
718
      insertDocid(newdocid3 + ".1", testDocument, SUCCESS, false);
719
      
720
      
721
      deleteDocid(newdocid2 + ".1", SUCCESS, false);
722
      deleteDocid(newdocid3 + ".1", SUCCESS, false);
723
      m.logout();
724
      
725
      // Clean the system up
726
      debug("Deleting test schemas from db");
727
      dbUpdate(deleteRegisteredIncludedTestSchemaSql,
728
          "SchemaRegistryTest.includedSchemaRegisterTest");
729
      
730
      debug("Deleting test schema files from server file system");
731
      FileUtil.deleteFile(serverSchemaLocation + includedSchemaFile1);
732
      FileUtil.deleteFile(serverSchemaLocation + includedSchemaFile2);
733
      FileUtil.deleteFile(serverSchemaLocation + includedSchemaFile3);
734
      FileUtil.deleteFile(serverSchemaLocation + includedSchemaFile4);
735
      
736
      debug("Refreshing the XMLSchemaService");
737
      httpPost(metacatUrl + "?action=refreshServices",
738
          new HashMap<String, String>());
739
      
740
    
741

    
742
    } catch (MetacatAuthException mae) {
743
      fail("Authorization failed: " + mae.getMessage());
744
    } catch (MetacatInaccessibleException mie) {
745
      fail("Metacat Inaccessible: " + mie.getMessage());
746
    } catch (IOException ioe) {
747
      fail("I/O Exception: " + ioe.getMessage());
748
    } catch (SQLException sqle) {
749
      fail("SQL Exception: " + sqle.getMessage());
750
    } catch (Exception e) {
751
      fail("General exception: " + e.getMessage());
752
    }
753
  }
754
	
755
	/**
756
	 * @param documentLocation
757
	 *            the path of the document to read.
758
	 * @return a string holding the contents of the document with the contextUrl
759
	 *         token replaced by the test.contextUrl property
760
	 */
761
	private String getTestDocument(String documentLocation) throws IOException,
762
			PropertyNotFoundException {
763
		String testDocument = null;
764
		try {
765
			testDocument = FileUtil.readFileToString(documentLocation);
766
		} catch (UtilException ue) {
767
			throw new IOException("Error reading file to string: " +  ue.getMessage());
768
		}
769

    
770
		String contextUrl = PropertyService.getProperty("test.contextUrl");
771
		testDocument = testDocument.replaceAll("@contextUrl@", contextUrl);
772

    
773
		return testDocument;
774
	}
775
	
776
	/**
777
	 * Insert a document into metacat via the metacat client.
778
	 * 
779
	 * @param docid
780
	 *            the id of the document to insert
781
	 * @param testdocument
782
	 *            the contents of the document
783
	 * @param result
784
	 *            do we expect this to succed or fail
785
	 * @param expectKarmaException
786
	 *            do we expect it to fail with a KarmaException
787
	 * @return the response that was passed back from metacat
788
	 */
789
	private String insertDocid(String docid, String testdocument, boolean result,
790
			boolean expectKarmaException) {
791
		debug("insertDocid(): docid=" + docid + " expectedResult=" + result
792
				+ " expectKarmaException=" + expectKarmaException);
793
		String response = null;
794
		try {
795
			response = m.insert(docid, new StringReader(testdocument), null);
796
			debug("expected result: " + result);
797
			if (result) {
798
				assertTrue(response, (response.indexOf("<success>") != -1));
799
				assertTrue(response, response.indexOf(docid) != -1);
800
			} else {
801
				debug("in else, checking: " + (response.indexOf("<success>") == -1));
802
				assertTrue(response, (response.indexOf("<success>") == -1));
803
			}
804
			debug("insertDocid():  response=" + response);
805
		} catch (MetacatInaccessibleException mie) {
806
			fail("Metacat Inaccessible:\n" + mie.getMessage());
807
		} catch (InsufficientKarmaException ike) {
808
			if (!expectKarmaException) {
809
				fail("Insufficient karma:\n" + ike.getMessage());
810
			}
811
		} catch (MetacatException me) {
812
			fail("Metacat Error:\n" + me.getMessage());
813
		} catch (Exception e) {
814
			fail("General exception:\n" + e.getMessage());
815
		}
816
		return response;
817
	}
818
	
819
	/**
820
	 * Try to insert a document into metacat. This is used when we expect a
821
	 * MetacatException
822
	 * 
823
	 * @param docid
824
	 *            the document id we are going to attempt to insert
825
	 * @param testdocument
826
	 *            the contents of the document we are going to attempt to insert
827
	 * @param expectedException
828
	 *            text that should be a substring of the MetacatException
829
	 *            message
830
	 */
831
	private void insertDocidExpectException(String docid, String testdocument, String expectedException) {
832
		debug("insertDocidExpectException(): docid=" + docid + " expectedException=" + expectedException);
833

    
834
		String response = null;
835
		try {
836
			response = m.insert(docid, new StringReader(testdocument), null);	
837
			fail("Expecting a MetacatException.  Instead, got response: " + response);
838
		} catch (MetacatInaccessibleException mie) {
839
			fail("Metacat Inaccessible:\n" + mie.getMessage());
840
		} catch (InsufficientKarmaException ike) {
841
			fail("Insufficient karma:\n" + ike.getMessage());
842
		} catch (MetacatException me) {
843
			assertTrue(me.getMessage(), me.getMessage().contains(expectedException));
844
		} catch (Exception e) {
845
			fail("General exception:\n" + e.getMessage());
846
		}
847
		
848
		
849
	}
850

    
851
	/**
852
	 * Delete a document into metacat. The expected result is passed as result
853
	 */
854
	private void deleteDocid(String docid, boolean result, boolean expectedKarmaFailure) {
855
		debug("deleteDocid(): docid=" + docid + " expectedResult=" + result
856
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
857
		try {
858
			Thread.sleep(5000);
859
			String response = m.delete(docid);
860
			if (result) {
861
				assertTrue(response, response.indexOf("<success>") != -1);
862
			} else {
863
				assertTrue(response, response.indexOf("<success>") == -1);
864
			}
865
			debug("deleteDocid():  response=" + response);
866
		} catch (MetacatInaccessibleException mie) {
867
			fail("Metacat Inaccessible:\n" + mie.getMessage());
868
		} catch (InsufficientKarmaException ike) {
869
			if (!expectedKarmaFailure) {
870
				fail("Insufficient karma:\n" + ike.getMessage());
871
			}
872
		} catch (MetacatException me) {
873
			if (result) {
874
				fail("Metacat Error:\n" + me.getMessage());
875
			} else {
876
				debug("Metacat Error:\n" + me.getMessage());
877
			}
878
		} catch (Exception e) {
879
			fail("General exception:\n" + e.getMessage());
880
		}
881
	}
882

    
883
	/**
884
	 * Create a hopefully unique docid for testing insert and update. Does not
885
	 * include the 'revision' part of the id.
886
	 * 
887
	 * @return a String docid based on the current date and time
888
	 */
889
	private String generateDocid() {
890
		try {
891
			Thread.sleep(1100);
892
		} catch (Exception e) {
893
			debug("Could not sleep: " + e.getMessage());
894
		}
895
		StringBuffer docid = new StringBuffer("test");
896
		docid.append(".");
897

    
898
		// Create a calendar to get the date formatted properly
899
		String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
900
		SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
901
		pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
902
		pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
903
		Calendar calendar = new GregorianCalendar(pdt);
904
		Date trialTime = new Date();
905
		calendar.setTime(trialTime);
906
		docid.append(calendar.get(Calendar.YEAR));
907
		docid.append(calendar.get(Calendar.DAY_OF_YEAR));
908
		docid.append(calendar.get(Calendar.HOUR_OF_DAY));
909
		docid.append(calendar.get(Calendar.MINUTE));
910
		docid.append(calendar.get(Calendar.SECOND));
911

    
912
		return docid.toString();
913
	}
914
	
915
}
(20-20/24)