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: leinfelder $'
8
 *     '$Date: 2010-12-27 11:25:59 -0800 (Mon, 27 Dec 2010) $'
9
 * '$Revision: 5757 $'
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.InputStream;
29
import java.io.InputStreamReader;
30
import java.io.Reader;
31
import java.io.StringReader;
32
import java.util.Calendar;
33
import java.util.Date;
34
import java.util.GregorianCalendar;
35
import java.util.SimpleTimeZone;
36
import java.util.TimeZone;
37

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

    
53
import org.apache.commons.io.IOUtils;
54

    
55
/**
56
 * A JUnit test for testing Metacat when Non Ascii Characters are inserted
57
 */
58
public class NonAsciiCharacterTest
59
    extends MCTestCase {
60

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

    
79
    private String prefix = "test";
80
    private String testdocument = "";
81

    
82
    private Metacat m;
83

    
84
    /**
85
     * These variables are for eml-2.0.1 only. For other eml versions,
86
     * this function might have to modified
87
     */
88

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

    
105
    private String testEmlCreatorBlock =
106
        "<creator scope=\"document\">                                       " +
107
        " <individualName>                                                  " +
108
        "    <surName>Smith</surName>                                       " +
109
        " </individualName>                                                 " +
110
        "</creator>                                                         ";
111

    
112
    private String testEmlContactBlock =
113
        "<contact scope=\"document\">                                       " +
114
        " <individualName>                                                  " +
115
        "    <surName>Jackson</surName>                                     " +
116
        " </individualName>                                                 " +
117
        "</contact>                                                         ";
118

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

    
129
        if (grantAccess) {
130
            accessBlock += "<allow>";
131
        }
132
        else {
133
            accessBlock += "<deny>";
134
        }
135

    
136
        accessBlock = accessBlock + "<principal>" + principal + "</principal>";
137

    
138
        if (all) {
139
            accessBlock += "<permission>all</permission>";
140
        }
141
        else {
142
            if (read) {
143
                accessBlock += "<permission>read</permission>";
144
            }
145
            if (write) {
146
                accessBlock += "<permission>write</permission>";
147
            }
148
            if (changePermission) {
149
                accessBlock += "<permission>changePermission</permission>";
150
            }
151
        }
152

    
153
        if (grantAccess) {
154
            accessBlock += "</allow>";
155
        }
156
        else {
157
            accessBlock += "</deny>";
158
        }
159
        accessBlock += "</access>";
160

    
161
        return accessBlock;
162

    
163
    }
164
    
165
    /**
166
     * Returns an xml squery that searches for the doc id in the
167
     * title of documents. This function is for eml-2.0.1+ only. For 
168
     * other eml versions, this function might have to modified.
169
     */
170
    private String getTestEmlQuery(String titlePart, String emlVersion) {
171

    
172
    	String docType;
173
    	if (emlVersion.equals(EML2_0_1)) {
174
    		docType = "eml://ecoinformatics.org/eml-2.0.1";
175
    	} else if (emlVersion.equals(EML2_1_0)) {
176
    		docType = "eml://ecoinformatics.org/eml-2.1.0";
177
    	} else { //if (emlVersion.equals(EML2_1_1)) {
178
    		docType = "eml://ecoinformatics.org/eml-2.1.1";
179
    	}
180
    	
181
        String sQuery = "";
182
        sQuery = 
183
        	"<pathquery version=\"1.0\">" +
184
        		"<meta_file_id>unspecified</meta_file_id>" +
185
        		"<querytitle>unspecified</querytitle>" + 
186
        		"<returnfield>dataset/title</returnfield>" +
187
        		"<returndoctype>" + docType + "</returndoctype>" +
188
        		"<querygroup operator=\"UNION\">" +
189
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
190
        				"<value>" + titlePart + "</value>" +
191
        				"<pathexpr>dataset/title</pathexpr>" +
192
        			"</queryterm>" +
193
        		"</querygroup>" +
194
        	"</pathquery>";
195

    
196
        return sQuery;
197
    }
198

    
199
    /**
200
     * Constructor to build the test
201
     *
202
     * @param name the name of the test method
203
     */
204
    public NonAsciiCharacterTest(String name) {
205
        super(name);
206
    }
207

    
208
    /**
209
     * Establish a testing framework by initializing appropriate objects
210
     */
211
    public void setUp() {
212
        try {
213
            System.err.println("Test Metacat: " + metacatUrl);
214
            m = MetacatFactory.createMetacatConnection(metacatUrl);
215
        }
216
        catch (MetacatInaccessibleException mie) {
217
            System.err.println("Metacat is: " + metacatUrl);
218
            fail("Metacat connection failed." + mie.getMessage());
219
        }
220
    }
221

    
222
    /**
223
     * Release any objects after tests are complete
224
     */
225
    public void tearDown() {
226
    }
227

    
228
    /**
229
     * Create a suite of tests to be run together
230
     */
231
    public static Test suite() {
232
        TestSuite suite = new TestSuite();
233
        suite.addTest(new NonAsciiCharacterTest("initialize"));
234
        // Test basic functions
235
        suite.addTest(new NonAsciiCharacterTest("invalidXMLCharacters201Test"));
236
        suite.addTest(new NonAsciiCharacterTest("invalidXMLCharacters210Test"));
237
        suite.addTest(new NonAsciiCharacterTest("symbolEncodedFormat201Test"));
238
        suite.addTest(new NonAsciiCharacterTest("symbolEncodedFormat210Test"));
239
        suite.addTest(new NonAsciiCharacterTest("quote201Test"));
240
        suite.addTest(new NonAsciiCharacterTest("quote210Test"));
241
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormat201Test"));
242
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormat210Test"));
243
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter201Test"));
244
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacter210Test"));
245

    
246
        return suite;
247
    }
248

    
249
    /**
250
     * Run an initial test that always passes to check that the test
251
     * harness is working.
252
     */
253
    public void initialize() {
254
        assertTrue(1 == 1);
255
    }
256

    
257
    /**
258
     * Test inserting an EML 2.0.1 document with > & <
259
     * should fail because this means an invalid xml document is being inserted
260
     */
261
    public void invalidXMLCharacters201Test() {
262
    	debug("\nRunning: invalidXMLCharacters201Test");
263
        try {
264
            String newdocid = generateDocid();
265
            m.login(username, password);
266
            testdocument = getTestEmlDoc("Checking > & < in doc: " + newdocid, EML2_0_1);
267
            insertDocid(newdocid + ".1", testdocument, FAILURE, true);
268
            m.logout();
269
        }
270
        catch (MetacatAuthException mae) {
271
            fail("Authorization failed:\n" + mae.getMessage());
272
        }
273
        catch (MetacatInaccessibleException mie) {
274
            fail("Metacat Inaccessible:\n" + mie.getMessage());
275
        }
276
        catch (Exception e) {
277
            fail("General exception:\n" + e.getMessage());
278
        }
279
    }
280
    
281
    /**
282
     * Test inserting an EML 2.1.0 document with > & <
283
     * should fail because this means an invalid xml document is being inserted
284
     */
285
    public void invalidXMLCharacters210Test() {
286
    	debug("\nRunning: invalidXMLCharacters210Test");
287
        try {
288
            String newdocid = generateDocid();
289
            m.login(username, password);
290
            testdocument = getTestEmlDoc("Checking > & < in doc: " + newdocid, EML2_1_0);
291
            insertDocid(newdocid + ".1", testdocument, FAILURE, true);
292
            m.logout();
293
        }
294
        catch (MetacatAuthException mae) {
295
            fail("Authorization failed:\n" + mae.getMessage());
296
        }
297
        catch (MetacatInaccessibleException mie) {
298
            fail("Metacat Inaccessible:\n" + mie.getMessage());
299
        }
300
        catch (Exception e) {
301
            fail("General exception:\n" + e.getMessage());
302
        }
303
    }
304

    
305
    /**
306
     * Test inserting and reading an EML 2.0.1 document with &gt; &amp; &lt;
307
     * Read should succeed since the same document should be read 
308
     * back from disk that was submitted. Query should succeed as 
309
     * well because the characters in this test are not changed in
310
     * the database.
311
     */
312
    public void symbolEncodedFormat201Test() {
313
    	debug("\nRunning: symbolEncodedFormat201Test");
314
        try {
315
            String newdocid = generateDocid();
316
            m.login(username, password);
317
            
318
            String testTitle = 
319
            	"Checking &gt; &lt; &quot; &apos; &amp; in doc: " + newdocid  + ".1";
320
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
321
            insertDocid(newdocid  + ".1", testdocument, SUCCESS, false);
322
            
323
            // this tests reading the document back from disk
324
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
325
            
326
            // this tests searching for the document in the database
327
            Thread.sleep(3000);
328
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_0_1, SUCCESS);
329
            
330
            deleteDocid(newdocid  + ".1", SUCCESS, false);
331
            
332
            m.logout();
333
        }
334
        catch (MetacatAuthException mae) {
335
            fail("Authorization failed:\n" + mae.getMessage());
336
        }
337
        catch (MetacatInaccessibleException mie) {
338
            fail("Metacat Inaccessible:\n" + mie.getMessage());
339
        }
340
        catch (Exception e) {
341
            fail("General exception:\n" + e.getMessage());
342
        }
343
    }
344
    
345
    /**
346
     * Test inserting and reading an EML 2.1.0 document with &gt; &amp; &lt;
347
     * Read should succeed since the same document should be read 
348
     * back from disk that was submitted. Query should succeed as 
349
     * well because the characters in this test are not changed in
350
     * the database.
351
     */
352
    public void symbolEncodedFormat210Test() {
353
    	debug("\nRunning: symbolEncodedFormat210Test");
354
        try {
355
            String newdocid = generateDocid();
356
            m.login(username, password);
357
            
358
            String testTitle = 
359
            	"Checking &gt; &lt; &quot; &apos; &amp; in doc: " + newdocid + ".1";
360
            testdocument = getTestEmlDoc(testTitle, EML2_1_0);
361
            insertDocid(newdocid  + ".1", testdocument, SUCCESS, false);
362
            
363
            // this tests reading the document back from disk
364
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
365
            
366
            // this tests searching for the document in the database
367
            Thread.sleep(3000);
368
            queryDocWhichHasTitle(newdocid  + ".1", testTitle, EML2_1_0, SUCCESS);
369
            
370
            deleteDocid(newdocid  + ".1", SUCCESS, false);
371
            
372
            m.logout();
373
        }
374
        catch (MetacatAuthException mae) {
375
            fail("Authorization failed:\n" + mae.getMessage());
376
        }
377
        catch (MetacatInaccessibleException mie) {
378
            fail("Metacat Inaccessible:\n" + mie.getMessage());
379
        }
380
        catch (Exception e) {
381
            fail("General exception:\n" + e.getMessage());
382
        }
383
    }
384

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

    
465
    /**
466
     * Test inserting and reading an EML 2.0.1 document with the code representation 
467
     * of a micro sign (&#181). Read should succeed since the same document should be 
468
     * read back from disk that was submitted.  Query should succeed because we look 
469
     * for the converted character (µ).
470
     */
471
    public void numericCharacterReferenceFormat201Test() {
472
    	debug("\nRunning: numericCharacterReferenceFormat201Test");
473
        try {
474
            String newdocid = generateDocid();
475
            m.login(username, password);
476
            
477
            String testTitle = "Checking &#181; in doc: " + newdocid  + ".1";
478
            String convertedTestTitle = "Checking µ in doc: " + newdocid  + ".1";
479
            
480
            testdocument = getTestEmlDoc(testTitle, EML2_0_1);
481
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
482

    
483
            // this tests reading the document back from disk
484
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
485
            
486
            // this tests searching for the document in the database
487
            Thread.sleep(3000);
488
            queryDocWhichHasTitle(newdocid  + ".1", convertedTestTitle, EML2_0_1, SUCCESS);
489
            
490
            deleteDocid(newdocid  + ".1", SUCCESS, false);
491
  
492
            m.logout();
493
        }
494
        catch (MetacatAuthException mae) {
495
            fail("Authorization failed:\n" + mae.getMessage());
496
        }
497
        catch (MetacatInaccessibleException mie) {
498
            fail("Metacat Inaccessible:\n" + mie.getMessage());
499
        }
500
        catch (Exception e) {
501
            fail("General exception:\n" + e.getMessage());
502
        }
503
    }
504

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

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

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

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

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

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

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

    
740
        return response;
741
    }
742

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

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

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

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

    
823
                if (!testDoc.equals(doc)) {
824
                    debug("doc    :" + doc);
825
                    debug("testDoc:" + testDoc);
826
                }
827

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

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

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

    
885
    }
886

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

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