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

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

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

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

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

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

    
335
			String testDocument = getTestDocument(testFileLocation + badSchemaLocationXMLFile);
336
			
337
			// login
338
			debug("logging in as: username=" + username + " password=" + password);
339
			m.login(username, password);
340
			
341
			// insert document.  We expect to fail with a MetacatException because the schemaLocation
342
			// does not exist.
343
			insertDocidExpectException(newdocid1 + ".1", testDocument, "Failed to read schema document");
344
	         Thread.sleep(2000);
345

    
346
			// Check the db for registered schemas.  We should find none.
347
			debug("Checking db for registered schemas");
348
			Vector<Hashtable<String,Object>> sqlResults = 
349
				dbSelect(getRegisteredTestSchemaSql, 
350
						"SchemaRegistryTest.newNonexistantSchemaLocationRegisterTest");
351
			if (sqlResults.size() != 0) {
352
				fail("Expected number of test schemas in the database is 0." +
353
						" The number found was: " + sqlResults.size());
354
			}
355
			
356
			
357
			// check the system for the schema files.  There should be none.
358
			debug("Checking server for registered schema file: " + serverSchemaLocation + goodSchemaFile1);
359
			if( FileUtil.getFileStatus(serverSchemaLocation + goodSchemaFile1) >= 
360
					FileUtil.EXISTS_ONLY) {
361
				fail("Found unexpected schema file on server: " + 
362
						serverSchemaLocation + goodSchemaFile1);
363
			}
364

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

    
384
			try {
385
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
386
			} catch (FileNotFoundException fnfe) {
387
				// Do nothing here. We are hoping that the file didn't exist.
388
			}
389

    
390
			debug("Refreshing the XMLSchemaService");
391
			httpPost(metacatUrl + "?action=refreshServices",
392
					new HashMap<String, String>());
393

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

    
418
			String newdocid1 = generateDocid();
419
			
420
			debug("Refreshing the XMLSchemaService");
421
			httpPost(metacatUrl + "?action=refreshServices",
422
					new HashMap<String, String>());
423

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

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

    
473
			try {
474
				FileUtil.deleteFile(serverSchemaLocation + goodSchemaFile2);
475
			} catch (FileNotFoundException fnfe) {
476
				// Do nothing here. We are hoping that the file didn't exist.
477
			}
478

    
479
			debug("Refreshing the XMLSchemaService");
480
			httpPost(metacatUrl + "?action=refreshServices",
481
					new HashMap<String, String>());
482

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

    
511
			// login
512
			debug("logging in as: username=" + username + " password=" + password);
513
			m.login(username, password);
514
			
515
			// insert good document.  We expect to succeed.
516
			String newdocid1 = generateDocid();
517
			String testDocument1 = getTestDocument(testFileLocation + goodSchemaXMLFile);
518
			insertDocid(newdocid1 + ".1", testDocument1, SUCCESS, false);
519

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

    
546
			debug("Refreshing the XMLSchemaService");
547
			httpPost(metacatUrl + "?action=refreshServices",
548
					new HashMap<String, String>());
549
			
550
			deleteDocid(newdocid1 + ".1", SUCCESS, false);
551

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

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

    
670
      String newdocid = generateDocid();
671
      
672
      debug("Refreshing the XMLSchemaService");
673
      httpPost(metacatUrl + "?action=refreshServices",
674
          new HashMap<String, String>());
675

    
676
      String testDocument = getTestDocument(testFileLocation + includedSchemaXMLFile);
677
      
678
      // login
679
      debug("logging in as: username=" + username + " password=" + password);
680
      m.login(username, password);
681
      
682
      // insert document.  We expect to succeed.
683
      insertDocid(newdocid + ".1", testDocument, SUCCESS, false);
684
      
685
      Thread.sleep(2000);
686

    
687
      
688
      debug("Checking db for registered schemas");
689
      Vector<Hashtable<String,Object>> sqlResults = 
690
        dbSelect(getRegisteredIncludedTestSchemaSql, 
691
            "SchemaRegistryTest.includedSchemaRegisterTest");
692
      if (sqlResults.size() != 1) {
693
        fail("Expected number of test schemas in the database is 1." +
694
            " The number found was: " + sqlResults.size());
695
      }
696
      deleteDocid(newdocid + ".1", SUCCESS, false);
697
      debug("Checking server for registered schema file: " + serverSchemaLocation + includedSchemaFile1);
698
      if( FileUtil.getFileStatus(serverSchemaLocation + includedSchemaFile1) < 
699
          FileUtil.EXISTS_READABLE) {
700
        fail("Could not find expected schema file on server: " + 
701
            serverSchemaLocation + includedSchemaFile1);
702
      }
703

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

    
754
    } catch (MetacatAuthException mae) {
755
      fail("Authorization failed: " + mae.getMessage());
756
    } catch (MetacatInaccessibleException mie) {
757
      fail("Metacat Inaccessible: " + mie.getMessage());
758
    } catch (IOException ioe) {
759
      fail("I/O Exception: " + ioe.getMessage());
760
    } catch (SQLException sqle) {
761
      fail("SQL Exception: " + sqle.getMessage());
762
    } catch (Exception e) {
763
      fail("General exception: " + e.getMessage());
764
    }
765
  }
766
	
767
	/**
768
	 * @param documentLocation
769
	 *            the path of the document to read.
770
	 * @return a string holding the contents of the document with the contextUrl
771
	 *         token replaced by the test.contextUrl property
772
	 */
773
	private String getTestDocument(String documentLocation) throws IOException,
774
			PropertyNotFoundException {
775
		String testDocument = null;
776
		try {
777
			testDocument = FileUtil.readFileToString(documentLocation);
778
		} catch (UtilException ue) {
779
			throw new IOException("Error reading file to string: " +  ue.getMessage());
780
		}
781

    
782
		String contextUrl = PropertyService.getProperty("test.contextUrl");
783
		testDocument = testDocument.replaceAll("@contextUrl@", contextUrl);
784

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

    
846
		String response = null;
847
		try {
848
			response = m.insert(docid, new StringReader(testdocument), null);	
849
			fail("Expecting a MetacatException.  Instead, got response: " + response);
850
		} catch (MetacatInaccessibleException mie) {
851
			fail("Metacat Inaccessible:\n" + mie.getMessage());
852
		} catch (InsufficientKarmaException ike) {
853
			fail("Insufficient karma:\n" + ike.getMessage());
854
		} catch (MetacatException me) {
855
			assertTrue(me.getMessage(), me.getMessage().contains(expectedException));
856
		} catch (Exception e) {
857
			fail("General exception:\n" + e.getMessage());
858
		}
859
		
860
		
861
	}
862

    
863
	/**
864
	 * Delete a document into metacat. The expected result is passed as result
865
	 */
866
	private void deleteDocid(String docid, boolean result, boolean expectedKarmaFailure) {
867
		debug("deleteDocid(): docid=" + docid + " expectedResult=" + result
868
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
869
		try {
870
			Thread.sleep(5000);
871
			String response = m.delete(docid);
872
			if (result) {
873
				assertTrue(response, response.indexOf("<success>") != -1);
874
			} else {
875
				assertTrue(response, response.indexOf("<success>") == -1);
876
			}
877
			debug("deleteDocid():  response=" + response);
878
		} catch (MetacatInaccessibleException mie) {
879
			fail("Metacat Inaccessible:\n" + mie.getMessage());
880
		} catch (InsufficientKarmaException ike) {
881
			if (!expectedKarmaFailure) {
882
				fail("Insufficient karma:\n" + ike.getMessage());
883
			}
884
		} catch (MetacatException me) {
885
			if (result) {
886
				fail("Metacat Error:\n" + me.getMessage());
887
			} else {
888
				debug("Metacat Error:\n" + me.getMessage());
889
			}
890
		} catch (Exception e) {
891
			fail("General exception:\n" + e.getMessage());
892
		}
893
	}
894

    
895
	/**
896
	 * Create a hopefully unique docid for testing insert and update. Does not
897
	 * include the 'revision' part of the id.
898
	 * 
899
	 * @return a String docid based on the current date and time
900
	 */
901
	private String generateDocid() {
902
		try {
903
			Thread.sleep(1100);
904
		} catch (Exception e) {
905
			debug("Could not sleep: " + e.getMessage());
906
		}
907
		StringBuffer docid = new StringBuffer("test");
908
		docid.append(".");
909

    
910
		// Create a calendar to get the date formatted properly
911
		String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
912
		SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
913
		pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
914
		pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
915
		Calendar calendar = new GregorianCalendar(pdt);
916
		Date trialTime = new Date();
917
		calendar.setTime(trialTime);
918
		docid.append(calendar.get(Calendar.YEAR));
919
		docid.append(calendar.get(Calendar.DAY_OF_YEAR));
920
		docid.append(calendar.get(Calendar.HOUR_OF_DAY));
921
		docid.append(calendar.get(Calendar.MINUTE));
922
		docid.append(calendar.get(Calendar.SECOND));
923

    
924
		return docid.toString();
925
	}
926
	
927
}
(26-26/30)