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:39:53 -0700 (Tue, 16 Sep 2008) $'
9
 * '$Revision: 4356 $'
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
            m.logout();
352
        }
353
        catch (MetacatAuthException mae) {
354
            fail("Authorization failed:\n" + mae.getMessage());
355
        }
356
        catch (MetacatInaccessibleException mie) {
357
            fail("Metacat Inaccessible:\n" + mie.getMessage());
358
        }
359
        catch (Exception e) {
360
            fail("General exception:\n" + e.getMessage());
361
        }
362
    }
363
    
364
    /**
365
     * Test inserting and reading an EML 2.1.0 document with &gt; &amp; &lt;
366
     * Read should succeed since the same document should be read 
367
     * back from disk that was submitted. Query should succeed as 
368
     * well because the characters in this test are not changed in
369
     * the database.
370
     */
371
    public void symbolEncodedFormat210Test() {
372
    	debug("\nRunning: symbolEncodedFormat210Test");
373
        try {
374
            String newdocid = generateDocid();
375
            m.login(username, password);
376
            
377
            String testTitle = 
378
            	"Checking &gt; &lt; &quot; &apos; &amp; in doc: " + newdocid + ".1";
379
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
380
            insertDocid(newdocid  + ".1", testdocument, SUCCESS, false);
381
            
382
            // this tests reading the document back from disk
383
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
384
            
385
            // this tests searching for the document in the database
386
            Thread.sleep(3000);
387
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_1_0, SUCCESS);
388
            
389
            m.logout();
390
        }
391
        catch (MetacatAuthException mae) {
392
            fail("Authorization failed:\n" + mae.getMessage());
393
        }
394
        catch (MetacatInaccessibleException mie) {
395
            fail("Metacat Inaccessible:\n" + mie.getMessage());
396
        }
397
        catch (Exception e) {
398
            fail("General exception:\n" + e.getMessage());
399
        }
400
    }
401

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

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

    
496
            // this tests reading the document back from disk
497
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
498
            
499
            // this tests searching for the document in the database
500
            Thread.sleep(3000);
501
            queryDocWhichHasTitle(newdocid  + ".1", convertedTestTitle, EML2_0_1, SUCCESS);
502
  
503
            m.logout();
504
        }
505
        catch (MetacatAuthException mae) {
506
            fail("Authorization failed:\n" + mae.getMessage());
507
        }
508
        catch (MetacatInaccessibleException mie) {
509
            fail("Metacat Inaccessible:\n" + mie.getMessage());
510
        }
511
        catch (Exception e) {
512
            fail("General exception:\n" + e.getMessage());
513
        }
514
    }
515

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

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

    
608
            // this tests reading the document back from disk
609
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
610
            
611
            // this tests searching for the document in the database
612
            Thread.sleep(3000);
613
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_1_0, SUCCESS);
614
            
615
            m.logout();
616
        }
617
        catch (MetacatAuthException mae) {
618
            fail("Authorization failed:\n" + mae.getMessage());
619
        }
620
        catch (MetacatInaccessibleException mie) {
621
            fail("Metacat Inaccessible:\n" + mie.getMessage());
622
        }
623
        catch (Exception e) {
624
            fail("General exception:\n" + e.getMessage());
625
        }
626
    }
627

    
628
    /**
629
     * Insert a document into metacat. The expected result is passed as result
630
     */
631
    private String insertDocid(String docid, String docText, boolean result,
632
                               boolean expectMetacatException) {
633
        String response = null;
634
        try {
635
            response = m.insert(docid,
636
                                new StringReader(docText), null);
637
            System.err.println(response);
638
            if (result) {
639
                assertTrue( (response.indexOf("<success>") != -1));
640
                assertTrue(response.indexOf(docid) != -1);
641
            }
642
            else {
643
                assertTrue( (response.indexOf("<success>") == -1));
644
            }
645
        }
646
        catch (MetacatInaccessibleException mie) {
647
            fail("Metacat Inaccessible:\n" + mie.getMessage());
648
        }
649
        catch (InsufficientKarmaException ike) {
650
                fail("Insufficient karma:\n" + ike.getMessage());
651
        }
652
        catch (MetacatException me) {
653
            if (!expectMetacatException) {
654
                fail("Metacat Error:\n" + me.getMessage());
655
            }
656
        }
657
        catch (Exception e) {
658
            fail("General exception:\n" + e.getMessage());
659
        }
660
        return response;
661
    }
662

    
663
    /**
664
     * Insert a document into metacat. The expected result is passed as result
665
     */
666
    private String uploadDocid(String docid, String filePath, boolean result,
667
                               boolean expectedKarmaException) {
668
        String response = null;
669
        try {
670
            response = m.upload(docid, new File(filePath));
671
            if (result) {
672
                assertTrue( (response.indexOf("<success>") != -1));
673
                assertTrue(response.indexOf(docid) != -1);
674
            }
675
            else {
676
                assertTrue( (response.indexOf("<success>") == -1));
677
            }
678
            System.err.println("respose from metacat: " + response);
679
        }
680
        catch (MetacatInaccessibleException mie) {
681
            fail("Metacat Inaccessible:\n" + mie.getMessage());
682
        }
683
        catch (InsufficientKarmaException ike) {
684
            if (!expectedKarmaException) {
685
                fail("Insufficient karma:\n" + ike.getMessage());
686
            }
687
        }
688
        catch (MetacatException me) {
689
            if (result) {
690
                fail("Metacat Error:\n" + me.getMessage());
691
            } else {
692
                System.err.println("Metacat Error:\n" + me.getMessage());
693
            }
694
        }
695
        catch (Exception e) {
696
            fail("General exception:\n" + e.getMessage());
697
        }
698
        return response;
699
    }
700

    
701
    /**
702
     * Update a document in metacat. The expected result is passed as result
703
     */
704
    private String updateDocid(String docid, String docText, boolean result,
705
                               boolean expectedKarmaFailure) {
706
        String response = null;
707
        try {
708
            response = m.update(docid,
709
                                new StringReader(testdocument), null);
710

    
711
            if (result) {
712
                assertTrue( (response.indexOf("<success>") != -1));
713
                assertTrue(response.indexOf(docid) != -1);
714
            }
715
            else {
716
                assertTrue( (response.indexOf("<success>") == -1));
717
            }
718
            System.err.println(response);
719
        }
720
        catch (MetacatInaccessibleException mie) {
721
            fail("Metacat Inaccessible:\n" + mie.getMessage());
722
        }
723
        catch (InsufficientKarmaException ike) {
724
            if (!expectedKarmaFailure) {
725
                fail("Insufficient karma:\n" + ike.getMessage());
726
            }
727
        }
728
        catch (MetacatException me) {
729
            if (result) {
730
                fail("Metacat Error:\n" + me.getMessage());
731
            } else {
732
                System.err.println("Metacat Error:\n" + me.getMessage());
733
            }
734
        }
735
        catch (Exception e) {
736
            fail("General exception:\n" + e.getMessage());
737
        }
738

    
739
        return response;
740
    }
741

    
742
    /**
743
     * Delete a document from metacat. The expected result is passed as result
744
     */
745
    private void deleteDocid(String docid, boolean result,
746
                             boolean expextedKarmaFailure) {
747
        try {
748
            String response = m.delete(docid);
749
            if (result) {
750
                assertTrue(response.indexOf("<success>") != -1);
751
            }
752
            else {
753
                assertTrue(response.indexOf("<success>") == -1);
754
            }
755
            System.err.println(response);
756
        }
757
        catch (MetacatInaccessibleException mie) {
758
            fail("Metacat Inaccessible:\n" + mie.getMessage());
759
        }
760
        catch (InsufficientKarmaException ike) {
761
            if(!expextedKarmaFailure){
762
                fail("Insufficient karma:\n" + ike.getMessage());
763
            }
764
        }
765
        catch (MetacatException me) {
766
            if (result) {
767
                fail("Metacat Error:\n" + me.getMessage());
768
            } else {
769
                System.err.println("Metacat Error:\n" + me.getMessage());
770
            }
771
        }
772
        catch (Exception e) {
773
            fail("General exception:\n" + e.getMessage());
774
        }
775
    }
776

    
777
    /**
778
     * Read a document from metacat. The expected result is passed as result
779
     */
780
    private void readDocid(String docid, boolean result,
781
                           boolean expextedKarmaFailure) {
782
        try {
783
            Reader r = m.read(docid);
784
            String response = IOUtil.getAsString(r, true);
785

    
786
            if (!result) {
787
                assertTrue(response.indexOf("<success>") == -1);
788
            }
789
            // System.err.println(response);
790
        }
791
        catch (MetacatInaccessibleException mie) {
792
            fail("Metacat Inaccessible:\n" + mie.getMessage());
793
        }
794
        catch (InsufficientKarmaException ike) {
795
            if (!expextedKarmaFailure) {
796
                fail("Insufficient karma:\n" + ike.getMessage());
797
            }
798
        }
799
        catch (MetacatException me) {
800
            fail("Metacat Error:\n" + me.getMessage());
801
        }
802
        catch (Exception e) {
803
            fail("General exception:\n" + e.getMessage());
804
        }
805
    }
806

    
807
    /**
808
     * Read a document from metacat and check if it is equal to a given string.
809
     * The expected result is passed as result
810
     */
811
    private void readDocidWhichEqualsDoc(String docid, String testDoc,
812
                                         boolean result,
813
                                         boolean expectedKarmaFailure) {
814
        try {
815
            Reader r = m.read(docid);
816
            String doc = IOUtil.getAsString(r, true);
817
            if (result) {
818

    
819
                if (!testDoc.equals(doc)) {
820
                    System.out.println("doc    :" + doc);
821
                    System.out.println("testDoc:" + testDoc);
822
                }
823

    
824
                assertTrue(testDoc.equals(doc));
825
            }
826
            else {
827
                assertTrue(doc.indexOf("<error>") != -1);
828
            }
829
        }
830
        catch (MetacatInaccessibleException mie) {
831
            fail("Metacat Inaccessible:\n" + mie.getMessage());
832
        }
833
        catch (InsufficientKarmaException ike) {
834
            if (!expectedKarmaFailure) {
835
                fail("Insufficient karma:\n" + ike.getMessage());
836
            }
837
        }
838
        catch (MetacatException me) {
839
            fail("Metacat Error:\n" + me.getMessage());
840
        }
841
        catch (Exception e) {
842
            fail("General exception:\n" + e.getMessage());
843
        }
844

    
845
    }
846
    
847
    /**
848
     * Query a document by looking for it's doc id in the title element.
849
     * Then check if the testTitle exists in the doc.
850
     * @param docId the id of the doc to look for
851
     * @param testTitle the title containing special characters
852
     * @param result are we expecting SUCCESS or FAILURE
853
     * @param expextedKarmaFailure
854
     */
855
    private void queryDocWhichHasTitle(String docId, String testTitle,
856
                                         String emlVersion, boolean result) {
857
        try {
858
            String sQuery = getTestEmlQuery(docId, emlVersion);
859
        	debug("sQuery: " + sQuery);
860
        	Reader queryReader = new StringReader(sQuery);
861
            Reader resultReader = m.query(queryReader);
862
            String queryResult = IOUtil.getAsString(resultReader, true);
863
            if (result) {
864
                if (!queryResult.contains(testTitle)) {
865
                    System.out.println("queryResult: " + queryResult);
866
                    System.out.println("does not contain title: " + testTitle);
867
                }
868

    
869
                assertTrue(queryResult.contains(testTitle));
870
            }
871
            else {
872
                assertTrue(queryResult.indexOf("<error>") != -1);
873
            }
874
        }
875
        catch (MetacatInaccessibleException mie) {
876
            fail("Metacat Inaccessible:\n" + mie.getMessage());
877
        }
878
        catch (Exception e) {
879
            fail("General exception:\n" + e.getMessage());
880
        }
881

    
882
    }
883

    
884
    /**
885
     * Create a hopefully unique docid for testing insert and update. Does
886
     * not include the 'revision' part of the id.
887
     *
888
     * @return a String docid based on the current date and time
889
     */
890
    private String generateDocid() {
891
        StringBuffer docid = new StringBuffer(prefix);
892
        docid.append(".");
893

    
894
        // Create a calendar to get the date formatted properly
895
        String[] ids = TimeZone.getAvailableIDs( -8 * 60 * 60 * 1000);
896
        SimpleTimeZone pdt = new SimpleTimeZone( -8 * 60 * 60 * 1000, ids[0]);
897
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
898
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
899
                       2 * 60 * 60 * 1000);
900
        Calendar calendar = new GregorianCalendar(pdt);
901
        Date trialTime = new Date();
902
        calendar.setTime(trialTime);
903
        docid.append(calendar.get(Calendar.YEAR));
904
        docid.append(calendar.get(Calendar.DAY_OF_YEAR));
905
        docid.append(calendar.get(Calendar.HOUR_OF_DAY));
906
        docid.append(calendar.get(Calendar.MINUTE));
907
        docid.append(calendar.get(Calendar.SECOND));
908
   	    //sometimes this number is not unique, so we append a random number
909
    	int random = (new Double(Math.random()*100)).intValue();
910
    	docid.append(random);
911
        return docid.toString();
912
    }
913
}
(9-9/19)