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-29 11:15:17 -0700 (Mon, 29 Sep 2008) $'
9
 * '$Revision: 4407 $'
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.Reader;
29
import java.io.StringReader;
30
import java.util.Calendar;
31
import java.util.Date;
32
import java.util.GregorianCalendar;
33
import java.util.SimpleTimeZone;
34
import java.util.TimeZone;
35

    
36
import edu.ucsb.nceas.MCTestCase;
37
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
38
import edu.ucsb.nceas.metacat.client.Metacat;
39
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
40
import edu.ucsb.nceas.metacat.client.MetacatException;
41
import edu.ucsb.nceas.metacat.client.MetacatFactory;
42
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
43
import edu.ucsb.nceas.metacat.service.PropertyService;
44
import edu.ucsb.nceas.utilities.IOUtil;
45
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
46
import junit.framework.Test;
47
import junit.framework.TestSuite;
48
import java.io.File;
49

    
50
/**
51
 * A JUnit test for testing Metacat when Non Ascii Characters are inserted
52
 */
53
public class NonAsciiCharacterTest
54
    extends MCTestCase {
55

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

    
74
    private String prefix = "test";
75
    private String testdocument = "";
76

    
77
    private Metacat m;
78

    
79
    /**
80
     * These variables are for eml-2.0.1 only. For other eml versions,
81
     * this function might have to modified
82
     */
83

    
84
    private String testEml_201_Header =
85
        "<?xml version=\"1.0\"?><eml:eml" +
86
        " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"" +
87
        " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
88
        " packageId=\"eml.1.1\" system=\"knb\"" +
89
        " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\"" +
90
        " scope=\"system\">";
91
    
92
    private String testEml_210_Header =
93
        "<?xml version=\"1.0\"?><eml:eml" +
94
        " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.0\"" +
95
        " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
96
        " packageId=\"eml.1.1\" system=\"knb\"" +
97
        " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.0 eml.xsd\"" +
98
        " scope=\"system\">";
99

    
100
    private String testEmlCreatorBlock =
101
        "<creator scope=\"document\">                                       " +
102
        " <individualName>                                                  " +
103
        "    <surName>Smith</surName>                                       " +
104
        " </individualName>                                                 " +
105
        "</creator>                                                         ";
106

    
107
    private String testEmlContactBlock =
108
        "<contact scope=\"document\">                                       " +
109
        " <individualName>                                                  " +
110
        "    <surName>Jackson</surName>                                     " +
111
        " </individualName>                                                 " +
112
        "</contact>                                                         ";
113

    
114
    /**
115
     * This function returns an access block based on the params passed
116
     */
117
    private String getAccessBlock(String principal, boolean grantAccess,
118
                                  boolean read, boolean write,
119
                                  boolean changePermission, boolean all) {
120
        String accessBlock = "<access " +
121
            "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\"" +
122
            " order=\"allowFirst\" scope=\"document\">";
123

    
124
        if (grantAccess) {
125
            accessBlock += "<allow>";
126
        }
127
        else {
128
            accessBlock += "<deny>";
129
        }
130

    
131
        accessBlock = accessBlock + "<principal>" + principal + "</principal>";
132

    
133
        if (all) {
134
            accessBlock += "<permission>all</permission>";
135
        }
136
        else {
137
            if (read) {
138
                accessBlock += "<permission>read</permission>";
139
            }
140
            if (write) {
141
                accessBlock += "<permission>write</permission>";
142
            }
143
            if (changePermission) {
144
                accessBlock += "<permission>changePermission</permission>";
145
            }
146
        }
147

    
148
        if (grantAccess) {
149
            accessBlock += "</allow>";
150
        }
151
        else {
152
            accessBlock += "</deny>";
153
        }
154
        accessBlock += "</access>";
155

    
156
        return accessBlock;
157

    
158
    }
159

    
160
    /**
161
     * This function returns a valid eml document with no access rules
162
     * This function is for eml-2.0.1 only. For other eml versions,
163
     * this function might have to modified
164
     */
165
    private String getTestEmlDoc(String title, String emlVersion) {
166

    
167
        String testDocument = "";
168

    
169
        String header;
170
		if (emlVersion == EML2_0_1) {
171
			header = testEml_201_Header;
172
		} else {
173
			header = testEml_210_Header;
174
		}
175
        
176
        testDocument = testDocument + header +
177
            "<dataset scope=\"document\"><title>" + title + "</title>" +
178
            testEmlCreatorBlock;
179

    
180
        testDocument += testEmlContactBlock;
181
        testDocument += getAccessBlock("public", true, true, false, false, false);
182
        testDocument += "</dataset>";
183
        testDocument += "</eml:eml>";
184

    
185
        return testDocument;
186
    }
187
    
188
    /**
189
     * Returns an xml squery that searches for the doc id in the
190
     * title of documents. This function is for eml-2.0.1 only. For 
191
     * other eml versions, this function might have to modified.
192
     */
193
    private String getTestEmlQuery(String docid, String emlVersion) {
194

    
195
    	String docType;
196
    	if (emlVersion.equals(EML2_0_1)) {
197
    		docType = "eml://ecoinformatics.org/eml-2.0.1";
198
    	} else {
199
    		docType = "eml://ecoinformatics.org/eml-2.1.0";
200
    	}
201
    	
202
        String sQuery = "";
203
        sQuery = 
204
        	"<pathquery version=\"1.0\">" +
205
        		"<meta_file_id>unspecified</meta_file_id>" +
206
        		"<querytitle>unspecified</querytitle>" + 
207
        		"<returnfield>dataset/title</returnfield>" +
208
        		"<returndoctype>" + docType + "</returndoctype>" +
209
        		"<querygroup operator=\"UNION\">" +
210
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
211
        				"<value>" + docid + "</value>" +
212
        				"<pathexpr>dataset/title</pathexpr>" +
213
        			"</queryterm>" +
214
        		"</querygroup>" +
215
        	"</pathquery>";
216

    
217
        return sQuery;
218
    }
219

    
220
    /**
221
     * Constructor to build the test
222
     *
223
     * @param name the name of the test method
224
     */
225
    public NonAsciiCharacterTest(String name) {
226
        super(name);
227
    }
228

    
229
    /**
230
     * Establish a testing framework by initializing appropriate objects
231
     */
232
    public void setUp() {
233
        try {
234
            System.err.println("Test Metacat: " + metacatUrl);
235
            m = MetacatFactory.createMetacatConnection(metacatUrl);
236
        }
237
        catch (MetacatInaccessibleException mie) {
238
            System.err.println("Metacat is: " + metacatUrl);
239
            fail("Metacat connection failed." + mie.getMessage());
240
        }
241
    }
242

    
243
    /**
244
     * Release any objects after tests are complete
245
     */
246
    public void tearDown() {
247
    }
248

    
249
    /**
250
     * Create a suite of tests to be run together
251
     */
252
    public static Test suite() {
253
        TestSuite suite = new TestSuite();
254
        suite.addTest(new NonAsciiCharacterTest("initialize"));
255
        // Test basic functions
256
        suite.addTest(new NonAsciiCharacterTest("invalidXMLCharacters201Test"));
257
        suite.addTest(new NonAsciiCharacterTest("invalidXMLCharacters210Test"));
258
        suite.addTest(new NonAsciiCharacterTest("symbolEncodedFormat201Test"));
259
        suite.addTest(new NonAsciiCharacterTest("symbolEncodedFormat210Test"));
260
        suite.addTest(new NonAsciiCharacterTest("quote201Test"));
261
        suite.addTest(new NonAsciiCharacterTest("quote210Test"));
262
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormat201Test"));
263
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormat210Test"));
264
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter201Test"));
265
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter210Test"));
266

    
267
        return suite;
268
    }
269

    
270
    /**
271
     * Run an initial test that always passes to check that the test
272
     * harness is working.
273
     */
274
    public void initialize() {
275
        assertTrue(1 == 1);
276
    }
277

    
278
    /**
279
     * Test inserting an EML 2.0.1 document with > & <
280
     * should fail because this means an invalid xml document is being inserted
281
     */
282
    public void invalidXMLCharacters201Test() {
283
    	debug("\nRunning: invalidXMLCharacters201Test");
284
        try {
285
            String newdocid = generateDocid();
286
            m.login(username, password);
287
            testdocument = getTestEmlDoc("Checking > & < in doc: " + newdocid, EML2_0_1);
288
            insertDocid(newdocid + ".1", testdocument, FAILURE, true);
289
            m.logout();
290
        }
291
        catch (MetacatAuthException mae) {
292
            fail("Authorization failed:\n" + mae.getMessage());
293
        }
294
        catch (MetacatInaccessibleException mie) {
295
            fail("Metacat Inaccessible:\n" + mie.getMessage());
296
        }
297
        catch (Exception e) {
298
            fail("General exception:\n" + e.getMessage());
299
        }
300
    }
301
    
302
    /**
303
     * Test inserting an EML 2.1.0 document with > & <
304
     * should fail because this means an invalid xml document is being inserted
305
     */
306
    public void invalidXMLCharacters210Test() {
307
    	debug("\nRunning: invalidXMLCharacters210Test");
308
        try {
309
            String newdocid = generateDocid();
310
            m.login(username, password);
311
            testdocument = getTestEmlDoc("Checking > & < in doc: " + newdocid, EML2_1_0);
312
            insertDocid(newdocid + ".1", testdocument, FAILURE, true);
313
            m.logout();
314
        }
315
        catch (MetacatAuthException mae) {
316
            fail("Authorization failed:\n" + mae.getMessage());
317
        }
318
        catch (MetacatInaccessibleException mie) {
319
            fail("Metacat Inaccessible:\n" + mie.getMessage());
320
        }
321
        catch (Exception e) {
322
            fail("General exception:\n" + e.getMessage());
323
        }
324
    }
325

    
326
    /**
327
     * Test inserting and reading an EML 2.0.1 document with &gt; &amp; &lt;
328
     * Read should succeed since the same document should be read 
329
     * back from disk that was submitted. Query should succeed as 
330
     * well because the characters in this test are not changed in
331
     * the database.
332
     */
333
    public void symbolEncodedFormat201Test() {
334
    	debug("\nRunning: symbolEncodedFormat201Test");
335
        try {
336
            String newdocid = generateDocid();
337
            m.login(username, password);
338
            
339
            String testTitle = 
340
            	"Checking &gt; &lt; &quot; &apos; &amp; in doc: " + newdocid  + ".1";
341
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
342
            insertDocid(newdocid  + ".1", testdocument, SUCCESS, false);
343
            
344
            // this tests reading the document back from disk
345
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
346
            
347
            // this tests searching for the document in the database
348
            Thread.sleep(3000);
349
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_0_1, SUCCESS);
350
            
351
            deleteDocid(newdocid  + ".1", SUCCESS, false);
352
            
353
            m.logout();
354
        }
355
        catch (MetacatAuthException mae) {
356
            fail("Authorization failed:\n" + mae.getMessage());
357
        }
358
        catch (MetacatInaccessibleException mie) {
359
            fail("Metacat Inaccessible:\n" + mie.getMessage());
360
        }
361
        catch (Exception e) {
362
            fail("General exception:\n" + e.getMessage());
363
        }
364
    }
365
    
366
    /**
367
     * Test inserting and reading an EML 2.1.0 document with &gt; &amp; &lt;
368
     * Read should succeed since the same document should be read 
369
     * back from disk that was submitted. Query should succeed as 
370
     * well because the characters in this test are not changed in
371
     * the database.
372
     */
373
    public void symbolEncodedFormat210Test() {
374
    	debug("\nRunning: symbolEncodedFormat210Test");
375
        try {
376
            String newdocid = generateDocid();
377
            m.login(username, password);
378
            
379
            String testTitle = 
380
            	"Checking &gt; &lt; &quot; &apos; &amp; in doc: " + newdocid + ".1";
381
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
382
            insertDocid(newdocid  + ".1", testdocument, SUCCESS, false);
383
            
384
            // this tests reading the document back from disk
385
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
386
            
387
            // this tests searching for the document in the database
388
            Thread.sleep(3000);
389
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_1_0, SUCCESS);
390
            
391
            deleteDocid(newdocid  + ".1", SUCCESS, false);
392
            
393
            m.logout();
394
        }
395
        catch (MetacatAuthException mae) {
396
            fail("Authorization failed:\n" + mae.getMessage());
397
        }
398
        catch (MetacatInaccessibleException mie) {
399
            fail("Metacat Inaccessible:\n" + mie.getMessage());
400
        }
401
        catch (Exception e) {
402
            fail("General exception:\n" + e.getMessage());
403
        }
404
    }
405

    
406
    /**
407
     * Test inserting and reading an EML 2.0.1 document with single quote and double quote.
408
     * Read should succeed since the same document should be read back from disk 
409
     * that was submitted.  Query should succeed because we look for the converted
410
     * character (&apos; and &quot;).
411
     */
412
    public void quote201Test() {
413
    	debug("\nRunning: quote201Test");
414
        try {
415
            String newdocid = generateDocid();
416
            m.login(username, password);
417
            
418
            String testTitle = "Checking ' ` \" in doc: " + newdocid  + ".1";
419
            String convertedTestTitle = "Checking &apos; ` &quot; in doc: " + newdocid  + ".1";
420
            
421
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
422
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
423
            
424
            // this tests reading the document back from disk
425
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
426
            
427
            // this tests searching for the document in the database
428
            Thread.sleep(3000);
429
            queryDocWhichHasTitle(newdocid  + ".1", convertedTestTitle, EML2_0_1, SUCCESS);
430
            
431
            deleteDocid(newdocid  + ".1", SUCCESS, false);
432
            
433
            m.logout();
434
        }
435
        catch (MetacatAuthException mae) {
436
            fail("Authorization failed:\n" + mae.getMessage());
437
        }
438
        catch (MetacatInaccessibleException mie) {
439
            fail("Metacat Inaccessible:\n" + mie.getMessage());
440
        }
441
        catch (Exception e) {
442
            fail("General exception:\n" + e.getMessage());
443
        }
444
    }
445
    
446
    /**
447
     * Test inserting and reading an EML 2.1.0 document with single quote and double quote.
448
     * Read should succeed since the same document should be read back from disk 
449
     * that was submitted.  Query shoud succeed because we look for the converted
450
     * character (&apos; and &quot;).
451
     */
452
    public void quote210Test() {
453
    	debug("\nRunning: quote210Test");
454
        try {
455
            String newdocid = generateDocid();
456
            m.login(username, password);
457
            
458
            String testTitle = "Checking ' ` \" in doc: " + newdocid  + ".1";
459
            String convertedTestTitle = "Checking &apos; ` &quot; in doc: " + newdocid  + ".1";
460
            
461
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
462
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
463
            
464
            // this tests reading the document back from disk
465
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
466
            
467
            // this tests searching for the document in the database
468
            Thread.sleep(3000);
469
            queryDocWhichHasTitle(newdocid  + ".1", convertedTestTitle, EML2_1_0, SUCCESS);
470
            
471
            deleteDocid(newdocid  + ".1", SUCCESS, false);
472
            
473
            m.logout();
474
        }
475
        catch (MetacatAuthException mae) {
476
            fail("Authorization failed:\n" + mae.getMessage());
477
        }
478
        catch (MetacatInaccessibleException mie) {
479
            fail("Metacat Inaccessible:\n" + mie.getMessage());
480
        }
481
        catch (Exception e) {
482
            fail("General exception:\n" + e.getMessage());
483
        }
484
    }
485

    
486
    /**
487
     * Test inserting and reading an EML 2.0.1 document with the code representation 
488
     * of a micro sign (&#181). Read should succeed since the same document should be 
489
     * read back from disk that was submitted.  Query should succeed because we look 
490
     * for the converted character (µ).
491
     */
492
    public void numericCharacterReferenceFormat201Test() {
493
    	debug("\nRunning: numericCharacterReferenceFormat201Test");
494
        try {
495
            String newdocid = generateDocid();
496
            m.login(username, password);
497
            
498
            String testTitle = "Checking &#181; in doc: " + newdocid  + ".1";
499
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
500
            
501
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
502
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
503

    
504
            // this tests reading the document back from disk
505
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
506
            
507
            // this tests searching for the document in the database
508
            Thread.sleep(3000);
509
            queryDocWhichHasTitle(newdocid  + ".1", convertedTestTitle, EML2_0_1, SUCCESS);
510
            
511
            deleteDocid(newdocid  + ".1", SUCCESS, false);
512
  
513
            m.logout();
514
        }
515
        catch (MetacatAuthException mae) {
516
            fail("Authorization failed:\n" + mae.getMessage());
517
        }
518
        catch (MetacatInaccessibleException mie) {
519
            fail("Metacat Inaccessible:\n" + mie.getMessage());
520
        }
521
        catch (Exception e) {
522
            fail("General exception:\n" + e.getMessage());
523
        }
524
    }
525

    
526
    /**
527
     * Test inserting and reading an EML 2.1.0 document with the code representation 
528
     * of a micro sign (&#181). Read should succeed since the same document should be 
529
     * read back from disk that was submitted.  Query should succeed because we look 
530
     * for the converted character (µ).
531
     */
532
    public void numericCharacterReferenceFormat210Test() {
533
    	debug("\nRunning: numericCharacterReferenceFormat210Test");
534
        try {
535
            String newdocid = generateDocid();
536
            m.login(username, password);
537
            
538
            String testTitle = "Checking &#181; in doc: " + newdocid  + ".1";
539
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
540
            
541
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
542
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
543
            
544
            // this tests reading the document back from disk
545
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
546
            
547
            // this tests searching for the document in the database
548
            Thread.sleep(3000);
549
            queryDocWhichHasTitle(newdocid  + ".1", convertedTestTitle, EML2_1_0, SUCCESS);
550
            
551
            deleteDocid(newdocid  + ".1", SUCCESS, false);
552
            
553
            m.logout();
554
        }
555
        catch (MetacatAuthException mae) {
556
            fail("Authorization failed:\n" + mae.getMessage());
557
        }
558
        catch (MetacatInaccessibleException mie) {
559
            fail("Metacat Inaccessible:\n" + mie.getMessage());
560
        }
561
        catch (Exception e) {
562
            fail("General exception:\n" + e.getMessage());
563
        }
564
    }
565

    
566
    /**
567
     * Test inserting and reading an EML 2.0.1 document with the micro sign (µ). 
568
     * Read should succeed since the same document should be read back from disk 
569
     * that was submitted.  Query should succeed because we look for the same 
570
     * character (µ).
571
     */
572
    public void nonLatinUnicodeCharacter201Test() {
573
    	debug("\nRunning: nonLatinUnicodeCharacter201Test");
574
        try {
575
            String newdocid = generateDocid();
576
            m.login(username, password);
577
            
578
            String testTitle = "Checking characters like µ in doc: " + newdocid  + ".1";
579
            
580
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
581
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
582
            
583
            // this tests reading the document back from disk
584
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
585
            
586
            // this tests searching for the document in the database
587
            Thread.sleep(3000);
588
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_0_1, SUCCESS);
589
            
590
            deleteDocid(newdocid  + ".1", SUCCESS, false);
591
            
592
            m.logout();
593
        }
594
        catch (MetacatAuthException mae) {
595
            fail("Authorization failed:\n" + mae.getMessage());
596
        }
597
        catch (MetacatInaccessibleException mie) {
598
            fail("Metacat Inaccessible:\n" + mie.getMessage());
599
        }
600
        catch (Exception e) {
601
            fail("General exception:\n" + e.getMessage());
602
        }
603
    }
604
    
605
    /**
606
     * Test inserting and reading an EML 2.1.0 document with the micro sign (µ). 
607
     * Read should succeed since the same document should be read back from disk 
608
     * that was submitted.  Query should succeed because we look for the same 
609
     * character (µ).
610
     */
611
    public void nonLatinUnicodeCharacter210Test() {
612
    	debug("\nRunning: nonLatinUnicodeCharacter210Test");
613
        try {
614
            String newdocid = generateDocid();
615
            m.login(username, password);
616
            
617
            String testTitle = "Checking characters like µ in doc: " + newdocid  + ".1";
618
            
619
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
620
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
621

    
622
            // this tests reading the document back from disk
623
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
624
            
625
            // this tests searching for the document in the database
626
            Thread.sleep(3000);
627
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_1_0, SUCCESS);
628
            
629
            deleteDocid(newdocid  + ".1", SUCCESS, false);
630
            
631
            m.logout();
632
        }
633
        catch (MetacatAuthException mae) {
634
            fail("Authorization failed:\n" + mae.getMessage());
635
        }
636
        catch (MetacatInaccessibleException mie) {
637
            fail("Metacat Inaccessible:\n" + mie.getMessage());
638
        }
639
        catch (Exception e) {
640
            fail("General exception:\n" + e.getMessage());
641
        }
642
    }
643

    
644
    /**
645
     * Insert a document into metacat. The expected result is passed as result
646
     */
647
    private String insertDocid(String docid, String docText, boolean result,
648
                               boolean expectMetacatException) {
649
        String response = null;
650
        try {
651
            response = m.insert(docid,
652
                                new StringReader(docText), null);
653
            System.err.println(response);
654
            if (result) {
655
                assertTrue( (response.indexOf("<success>") != -1));
656
                assertTrue(response.indexOf(docid) != -1);
657
            }
658
            else {
659
                assertTrue( (response.indexOf("<success>") == -1));
660
            }
661
        }
662
        catch (MetacatInaccessibleException mie) {
663
            fail("Metacat Inaccessible:\n" + mie.getMessage());
664
        }
665
        catch (InsufficientKarmaException ike) {
666
                fail("Insufficient karma:\n" + ike.getMessage());
667
        }
668
        catch (MetacatException me) {
669
            if (!expectMetacatException) {
670
                fail("Metacat Error:\n" + me.getMessage());
671
            }
672
        }
673
        catch (Exception e) {
674
            fail("General exception:\n" + e.getMessage());
675
        }
676
        return response;
677
    }
678

    
679
    /**
680
     * Insert a document into metacat. The expected result is passed as result
681
     */
682
    private String uploadDocid(String docid, String filePath, boolean result,
683
                               boolean expectedKarmaException) {
684
        String response = null;
685
        try {
686
            response = m.upload(docid, new File(filePath));
687
            if (result) {
688
                assertTrue( (response.indexOf("<success>") != -1));
689
                assertTrue(response.indexOf(docid) != -1);
690
            }
691
            else {
692
                assertTrue( (response.indexOf("<success>") == -1));
693
            }
694
            System.err.println("respose from metacat: " + response);
695
        }
696
        catch (MetacatInaccessibleException mie) {
697
            fail("Metacat Inaccessible:\n" + mie.getMessage());
698
        }
699
        catch (InsufficientKarmaException ike) {
700
            if (!expectedKarmaException) {
701
                fail("Insufficient karma:\n" + ike.getMessage());
702
            }
703
        }
704
        catch (MetacatException me) {
705
            if (result) {
706
                fail("Metacat Error:\n" + me.getMessage());
707
            } else {
708
                System.err.println("Metacat Error:\n" + me.getMessage());
709
            }
710
        }
711
        catch (Exception e) {
712
            fail("General exception:\n" + e.getMessage());
713
        }
714
        return response;
715
    }
716

    
717
    /**
718
     * Update a document in metacat. The expected result is passed as result
719
     */
720
    private String updateDocid(String docid, String docText, boolean result,
721
                               boolean expectedKarmaFailure) {
722
        String response = null;
723
        try {
724
            response = m.update(docid,
725
                                new StringReader(testdocument), null);
726

    
727
            if (result) {
728
                assertTrue( (response.indexOf("<success>") != -1));
729
                assertTrue(response.indexOf(docid) != -1);
730
            }
731
            else {
732
                assertTrue( (response.indexOf("<success>") == -1));
733
            }
734
            System.err.println(response);
735
        }
736
        catch (MetacatInaccessibleException mie) {
737
            fail("Metacat Inaccessible:\n" + mie.getMessage());
738
        }
739
        catch (InsufficientKarmaException ike) {
740
            if (!expectedKarmaFailure) {
741
                fail("Insufficient karma:\n" + ike.getMessage());
742
            }
743
        }
744
        catch (MetacatException me) {
745
            if (result) {
746
                fail("Metacat Error:\n" + me.getMessage());
747
            } else {
748
                System.err.println("Metacat Error:\n" + me.getMessage());
749
            }
750
        }
751
        catch (Exception e) {
752
            fail("General exception:\n" + e.getMessage());
753
        }
754

    
755
        return response;
756
    }
757

    
758
    /**
759
     * Delete a document from metacat. The expected result is passed as result
760
     */
761
    private void deleteDocid(String docid, boolean result,
762
                             boolean expextedKarmaFailure) {
763
        try {
764
            String response = m.delete(docid);
765
            if (result) {
766
                assertTrue(response.indexOf("<success>") != -1);
767
            }
768
            else {
769
                assertTrue(response.indexOf("<success>") == -1);
770
            }
771
            System.err.println(response);
772
        }
773
        catch (MetacatInaccessibleException mie) {
774
            fail("Metacat Inaccessible:\n" + mie.getMessage());
775
        }
776
        catch (InsufficientKarmaException ike) {
777
            if(!expextedKarmaFailure){
778
                fail("Insufficient karma:\n" + ike.getMessage());
779
            }
780
        }
781
        catch (MetacatException me) {
782
            if (result) {
783
                fail("Metacat Error:\n" + me.getMessage());
784
            } else {
785
                System.err.println("Metacat Error:\n" + me.getMessage());
786
            }
787
        }
788
        catch (Exception e) {
789
            fail("General exception:\n" + e.getMessage());
790
        }
791
    }
792

    
793
    /**
794
     * Read a document from metacat. The expected result is passed as result
795
     */
796
    private void readDocid(String docid, boolean result,
797
                           boolean expextedKarmaFailure) {
798
        try {
799
            Reader r = m.read(docid);
800
            String response = IOUtil.getAsString(r, true);
801

    
802
            if (!result) {
803
                assertTrue(response.indexOf("<success>") == -1);
804
            }
805
            // System.err.println(response);
806
        }
807
        catch (MetacatInaccessibleException mie) {
808
            fail("Metacat Inaccessible:\n" + mie.getMessage());
809
        }
810
        catch (InsufficientKarmaException ike) {
811
            if (!expextedKarmaFailure) {
812
                fail("Insufficient karma:\n" + ike.getMessage());
813
            }
814
        }
815
        catch (MetacatException me) {
816
            fail("Metacat Error:\n" + me.getMessage());
817
        }
818
        catch (Exception e) {
819
            fail("General exception:\n" + e.getMessage());
820
        }
821
    }
822

    
823
    /**
824
     * Read a document from metacat and check if it is equal to a given string.
825
     * The expected result is passed as result
826
     */
827
    private void readDocidWhichEqualsDoc(String docid, String testDoc,
828
                                         boolean result,
829
                                         boolean expectedKarmaFailure) {
830
        try {
831
            Reader r = m.read(docid);
832
            String doc = IOUtil.getAsString(r, true);
833
            if (result) {
834

    
835
                if (!testDoc.equals(doc)) {
836
                    debug("doc    :" + doc);
837
                    debug("testDoc:" + testDoc);
838
                }
839

    
840
                assertTrue(testDoc.equals(doc));
841
            }
842
            else {
843
                assertTrue(doc.indexOf("<error>") != -1);
844
            }
845
        }
846
        catch (MetacatInaccessibleException mie) {
847
            fail("Metacat Inaccessible:\n" + mie.getMessage());
848
        }
849
        catch (InsufficientKarmaException ike) {
850
            if (!expectedKarmaFailure) {
851
                fail("Insufficient karma:\n" + ike.getMessage());
852
            }
853
        }
854
        catch (MetacatException me) {
855
            fail("Metacat Error:\n" + me.getMessage());
856
        }
857
        catch (Exception e) {
858
            fail("General exception:\n" + e.getMessage());
859
        }
860

    
861
    }
862
    
863
    /**
864
     * Query a document by looking for it's doc id in the title element.
865
     * Then check if the testTitle exists in the doc.
866
     * @param docId the id of the doc to look for
867
     * @param testTitle the title containing special characters
868
     * @param result are we expecting SUCCESS or FAILURE
869
     * @param expextedKarmaFailure
870
     */
871
    private void queryDocWhichHasTitle(String docId, String testTitle,
872
                                         String emlVersion, boolean result) {
873
        try {
874
            String sQuery = getTestEmlQuery(docId, emlVersion);
875
        	Reader queryReader = new StringReader(sQuery);
876
            Reader resultReader = m.query(queryReader);
877
            String queryResult = IOUtil.getAsString(resultReader, true);
878
            if (result) {
879
                if (!queryResult.contains(testTitle)) {
880
                    debug("queryResult: " + queryResult);
881
                    debug("does not contain title: " + testTitle);
882
                }
883

    
884
                assertTrue(queryResult.contains(testTitle));
885
            }
886
            else {
887
                assertTrue(queryResult.indexOf("<error>") != -1);
888
            }
889
        }
890
        catch (MetacatInaccessibleException mie) {
891
            fail("Metacat Inaccessible:\n" + mie.getMessage());
892
        }
893
        catch (Exception e) {
894
            fail("General exception:\n" + e.getMessage());
895
        }
896

    
897
    }
898

    
899
    /**
900
     * Create a hopefully unique docid for testing insert and update. Does
901
     * not include the 'revision' part of the id.
902
     *
903
     * @return a String docid based on the current date and time
904
     */
905
    private String generateDocid() {
906
        StringBuffer docid = new StringBuffer(prefix);
907
        docid.append(".");
908

    
909
        // Create a calendar to get the date formatted properly
910
        String[] ids = TimeZone.getAvailableIDs( -8 * 60 * 60 * 1000);
911
        SimpleTimeZone pdt = new SimpleTimeZone( -8 * 60 * 60 * 1000, ids[0]);
912
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
913
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
914
                       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
   	    //sometimes this number is not unique, so we append a random number
924
    	int random = (new Double(Math.random()*100)).intValue();
925
    	docid.append(random);
926
        return docid.toString();
927
    }
928
}
(9-9/19)