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-04-02 16:28:31 -0700 (Wed, 02 Apr 2008) $'
9
 * '$Revision: 3780 $'
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.metacat.MetaCatUtil;
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.utilities.IOUtil;
44
import junit.framework.Test;
45
import junit.framework.TestCase;
46
import junit.framework.TestSuite;
47
import java.io.File;
48

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

    
55
    private String metacatUrl = MetaCatUtil.getOption("metacatUrl");;
56
    private String username = MetaCatUtil.getOption("mcuser");
57
    private String password = MetaCatUtil.getOption("mcpassword");
58
    private String anotheruser = MetaCatUtil.getOption("mcanotheruser");
59
    private String anotherpassword = MetaCatUtil.getOption("mcanotherpassword");
60
    private String prefix = "test";
61
    private String newdocid = null;
62
    private String testdocument = "";
63

    
64
    private Metacat m;
65

    
66
    private boolean SUCCESS = true;
67
    private boolean FAILURE = false;
68

    
69
    /**
70
     * These variables are for eml-2.0.1 only. For other eml versions,
71
     * this function might have to modified
72
     */
73

    
74
    private String testEml_Header =
75
        "<?xml version=\"1.0\"?><eml:eml" +
76
        " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"" +
77
        " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
78
        " packageId=\"eml.1.1\" system=\"knb\"" +
79
        " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\"" +
80
        " scope=\"system\">";
81

    
82
    private String testEmlCreatorBlock =
83
        "<creator scope=\"document\">                                       " +
84
        " <individualName>                                                  " +
85
        "    <surName>Smith</surName>                                       " +
86
        " </individualName>                                                 " +
87
        "</creator>                                                         ";
88

    
89
    private String testEmlContactBlock =
90
        "<contact scope=\"document\">                                       " +
91
        " <individualName>                                                  " +
92
        "    <surName>Jackson</surName>                                     " +
93
        " </individualName>                                                 " +
94
        "</contact>                                                         ";
95

    
96
    /**
97
     * This function returns an access block based on the params passed
98
     */
99
    private String getAccessBlock(String principal, boolean grantAccess,
100
                                  boolean read, boolean write,
101
                                  boolean changePermission, boolean all) {
102
        String accessBlock = "<access " +
103
            "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\"" +
104
            " order=\"allowFirst\" scope=\"document\">";
105

    
106
        if (grantAccess) {
107
            accessBlock += "<allow>";
108
        }
109
        else {
110
            accessBlock += "<deny>";
111
        }
112

    
113
        accessBlock = accessBlock + "<principal>" + principal + "</principal>";
114

    
115
        if (all) {
116
            accessBlock += "<permission>all</permission>";
117
        }
118
        else {
119
            if (read) {
120
                accessBlock += "<permission>read</permission>";
121
            }
122
            if (write) {
123
                accessBlock += "<permission>write</permission>";
124
            }
125
            if (changePermission) {
126
                accessBlock += "<permission>changePermission</permission>";
127
            }
128
        }
129

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

    
138
        return accessBlock;
139

    
140
    }
141

    
142
    /**
143
     * This function returns a valid eml document with no access rules
144
     * This function is for eml-2.0.1 only. For other eml versions,
145
     * this function might have to modified
146
     */
147
    private String getTestEmlDoc(String title) {
148

    
149
        String testDocument = "";
150
        testDocument = testDocument + testEml_Header +
151
            "<dataset scope=\"document\"><title>" + title + "</title>" +
152
            testEmlCreatorBlock;
153

    
154
        testDocument += testEmlContactBlock;
155
        testDocument += getAccessBlock("public", true, true, false, false, false);
156
        testDocument += "</dataset>";
157
        testDocument += "</eml:eml>";
158

    
159
        return testDocument;
160
    }
161

    
162
    /**
163
     * Constructor to build the test
164
     *
165
     * @param name the name of the test method
166
     */
167
    public NonAsciiCharacterTest(String name) {
168
        super(name);
169
        newdocid = generateDocid();
170
    }
171

    
172
    /**
173
     * Establish a testing framework by initializing appropriate objects
174
     */
175
    public void setUp() {
176
        try {
177
            System.err.println("Test Metacat: " + metacatUrl);
178
            m = MetacatFactory.createMetacatConnection(metacatUrl);
179
        }
180
        catch (MetacatInaccessibleException mie) {
181
            System.err.println("Metacat is: " + metacatUrl);
182
            fail("Metacat connection failed." + mie.getMessage());
183
        }
184
    }
185

    
186
    /**
187
     * Release any objects after tests are complete
188
     */
189
    public void tearDown() {
190
    }
191

    
192
    /**
193
     * Create a suite of tests to be run together
194
     */
195
    public static Test suite() {
196
        TestSuite suite = new TestSuite();
197
        suite.addTest(new NonAsciiCharacterTest("initialize"));
198
        // Test basic functions
199
        suite.addTest(new NonAsciiCharacterTest("invalidXMLCharactersTest"));
200
        suite.addTest(new NonAsciiCharacterTest("symbolEncodedFormatTest"));
201
        suite.addTest(new NonAsciiCharacterTest("quoteTest"));
202
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormatTest"));
203
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacterTest"));
204

    
205
        return suite;
206
    }
207

    
208
    /**
209
     * Run an initial test that always passes to check that the test
210
     * harness is working.
211
     */
212
    public void initialize() {
213
        assertTrue(1 == 1);
214
    }
215

    
216

    
217
    /** *********
218
     * Test inserting document with > & <
219
     * should fail because this means an invalid xml document is being inserted
220
     */
221
    public void invalidXMLCharactersTest() {
222
        try {
223
            newdocid = generateDocid();
224
            m.login(username, password);
225
            testdocument = getTestEmlDoc("Checking > & <");
226
            insertDocid(newdocid + ".1", testdocument, FAILURE, true);
227
            m.logout();
228
        }
229
        catch (MetacatAuthException mae) {
230
            fail("Authorization failed:\n" + mae.getMessage());
231
        }
232
        catch (MetacatInaccessibleException mie) {
233
            fail("Metacat Inaccessible:\n" + mie.getMessage());
234
        }
235
        catch (Exception e) {
236
            fail("General exception:\n" + e.getMessage());
237
        }
238
    }
239

    
240

    
241
    /** *********
242
     * Test inserting document with &gt; &amp; &lt;
243
     * should fail because this means an invalid xml document is being inserted
244
     */
245
    public void symbolEncodedFormatTest() {
246
        try {
247
            newdocid = generateDocid();
248
            m.login(username, password);
249
            testdocument = getTestEmlDoc("Checking &gt; &lt; &quot; &apos; &amp;");
250
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
251
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
252
            m.logout();
253
        }
254
        catch (MetacatAuthException mae) {
255
            fail("Authorization failed:\n" + mae.getMessage());
256
        }
257
        catch (MetacatInaccessibleException mie) {
258
            fail("Metacat Inaccessible:\n" + mie.getMessage());
259
        }
260
        catch (Exception e) {
261
            fail("General exception:\n" + e.getMessage());
262
        }
263
    }
264

    
265

    
266
    /** *********
267
     * Test inserting document with single quote and double quote
268
     * should fail because this means an invalid xml document is being inserted
269
     */
270
    public void quoteTest() {
271
        try {
272
            newdocid = generateDocid();
273
            m.login(username, password);
274
            testdocument = getTestEmlDoc("Checking ' ` \"");
275
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
276
            testdocument = getTestEmlDoc("Checking &apos; ` &quot;");
277
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
278
            m.logout();
279
        }
280
        catch (MetacatAuthException mae) {
281
            fail("Authorization failed:\n" + mae.getMessage());
282
        }
283
        catch (MetacatInaccessibleException mie) {
284
            fail("Metacat Inaccessible:\n" + mie.getMessage());
285
        }
286
        catch (Exception e) {
287
            fail("General exception:\n" + e.getMessage());
288
        }
289
    }
290

    
291

    
292

    
293
    /** *********
294
     * Test inserting document with micro sign
295
     * should fail because this means an invalid xml document is being inserted
296
     */
297
    public void numericCharacterReferenceFormatTest() {
298
        try {
299
            newdocid = generateDocid();
300
            m.login(username, password);
301
            testdocument = getTestEmlDoc("Checking &#181;");
302
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
303
            testdocument = getTestEmlDoc("Checking µ");
304
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
305
            m.logout();
306
        }
307
        catch (MetacatAuthException mae) {
308
            fail("Authorization failed:\n" + mae.getMessage());
309
        }
310
        catch (MetacatInaccessibleException mie) {
311
            fail("Metacat Inaccessible:\n" + mie.getMessage());
312
        }
313
        catch (Exception e) {
314
            fail("General exception:\n" + e.getMessage());
315
        }
316
    }
317

    
318

    
319
    /** *********
320
     * Test inserting document with characters like µ
321
     * should fail because this means an invalid xml document is being inserted
322
     */
323
    public void nonLatinUnicodeCharacterTest() {
324
        try {
325
            newdocid = generateDocid();
326
            m.login(username, password);
327
            testdocument = getTestEmlDoc("Checking charcters like µ");
328
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
329
            //testdocument = getTestEmlDoc("Checking charcters like &#181;");
330
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
331
            m.logout();
332
        }
333
        catch (MetacatAuthException mae) {
334
            fail("Authorization failed:\n" + mae.getMessage());
335
        }
336
        catch (MetacatInaccessibleException mie) {
337
            fail("Metacat Inaccessible:\n" + mie.getMessage());
338
        }
339
        catch (Exception e) {
340
            fail("General exception:\n" + e.getMessage());
341
        }
342
    }
343

    
344
    /**
345
     * Insert a document into metacat. The expected result is passed as result
346
     */
347

    
348
    private String insertDocid(String docid, String docText, boolean result,
349
                               boolean expectMetacatException) {
350
        String response = null;
351
        try {
352
            response = m.insert(docid,
353
                                new StringReader(docText), null);
354
            System.err.println(response);
355
            if (result) {
356
                assertTrue( (response.indexOf("<success>") != -1));
357
                assertTrue(response.indexOf(docid) != -1);
358
            }
359
            else {
360
                assertTrue( (response.indexOf("<success>") == -1));
361
            }
362
        }
363
        catch (MetacatInaccessibleException mie) {
364
            fail("Metacat Inaccessible:\n" + mie.getMessage());
365
        }
366
        catch (InsufficientKarmaException ike) {
367
                fail("Insufficient karma:\n" + ike.getMessage());
368
        }
369
        catch (MetacatException me) {
370
            if (!expectMetacatException) {
371
                fail("Metacat Error:\n" + me.getMessage());
372
            }
373
        }
374
        catch (Exception e) {
375
            fail("General exception:\n" + e.getMessage());
376
        }
377
        return response;
378
    }
379

    
380
    /**
381
     * Insert a document into metacat. The expected result is passed as result
382
     */
383

    
384
    private String uploadDocid(String docid, String filePath, boolean result,
385
                               boolean expectedKarmaException) {
386
        String response = null;
387
        try {
388
            response = m.upload(docid, new File(filePath));
389
            if (result) {
390
                assertTrue( (response.indexOf("<success>") != -1));
391
                assertTrue(response.indexOf(docid) != -1);
392
            }
393
            else {
394
                assertTrue( (response.indexOf("<success>") == -1));
395
            }
396
            System.err.println("respose from metacat: " + response);
397
        }
398
        catch (MetacatInaccessibleException mie) {
399
            fail("Metacat Inaccessible:\n" + mie.getMessage());
400
        }
401
        catch (InsufficientKarmaException ike) {
402
            if (!expectedKarmaException) {
403
                fail("Insufficient karma:\n" + ike.getMessage());
404
            }
405
        }
406
        catch (MetacatException me) {
407
            if (result) {
408
                fail("Metacat Error:\n" + me.getMessage());
409
            } else {
410
                System.err.println("Metacat Error:\n" + me.getMessage());
411
            }
412
        }
413
        catch (Exception e) {
414
            fail("General exception:\n" + e.getMessage());
415
        }
416
        return response;
417
    }
418

    
419
    /**
420
     * Update a document in metacat. The expected result is passed as result
421
     */
422
    private String updateDocid(String docid, String docText, boolean result,
423
                               boolean expectedKarmaFailure) {
424
        String response = null;
425
        try {
426
            response = m.update(docid,
427
                                new StringReader(testdocument), null);
428

    
429
            if (result) {
430
                assertTrue( (response.indexOf("<success>") != -1));
431
                assertTrue(response.indexOf(docid) != -1);
432
            }
433
            else {
434
                assertTrue( (response.indexOf("<success>") == -1));
435
            }
436
            System.err.println(response);
437
        }
438
        catch (MetacatInaccessibleException mie) {
439
            fail("Metacat Inaccessible:\n" + mie.getMessage());
440
        }
441
        catch (InsufficientKarmaException ike) {
442
            if (!expectedKarmaFailure) {
443
                fail("Insufficient karma:\n" + ike.getMessage());
444
            }
445
        }
446
        catch (MetacatException me) {
447
            if (result) {
448
                fail("Metacat Error:\n" + me.getMessage());
449
            } else {
450
                System.err.println("Metacat Error:\n" + me.getMessage());
451
            }
452
        }
453
        catch (Exception e) {
454
            fail("General exception:\n" + e.getMessage());
455
        }
456

    
457
        return response;
458
    }
459

    
460
    /**
461
     * Delete a document into metacat. The expected result is passed as result
462
     */
463
    private void deleteDocid(String docid, boolean result,
464
                             boolean expextedKarmaFailure) {
465
        try {
466
            String response = m.delete(docid);
467
            if (result) {
468
                assertTrue(response.indexOf("<success>") != -1);
469
            }
470
            else {
471
                assertTrue(response.indexOf("<success>") == -1);
472
            }
473
            System.err.println(response);
474
        }
475
        catch (MetacatInaccessibleException mie) {
476
            fail("Metacat Inaccessible:\n" + mie.getMessage());
477
        }
478
        catch (InsufficientKarmaException ike) {
479
            if(!expextedKarmaFailure){
480
                fail("Insufficient karma:\n" + ike.getMessage());
481
            }
482
        }
483
        catch (MetacatException me) {
484
            if (result) {
485
                fail("Metacat Error:\n" + me.getMessage());
486
            } else {
487
                System.err.println("Metacat Error:\n" + me.getMessage());
488
            }
489
        }
490
        catch (Exception e) {
491
            fail("General exception:\n" + e.getMessage());
492
        }
493
    }
494

    
495
    /**
496
     * Read a document from metacat. The expected result is passed as result
497
     */
498
    private void readDocid(String docid, boolean result,
499
                           boolean expextedKarmaFailure) {
500
        try {
501
            Reader r = m.read(docid);
502
            String response = IOUtil.getAsString(r, true);
503

    
504
            if (!result) {
505
                assertTrue(response.indexOf("<success>") == -1);
506
            }
507
            // System.err.println(response);
508
        }
509
        catch (MetacatInaccessibleException mie) {
510
            fail("Metacat Inaccessible:\n" + mie.getMessage());
511
        }
512
        catch (InsufficientKarmaException ike) {
513
            if (!expextedKarmaFailure) {
514
                fail("Insufficient karma:\n" + ike.getMessage());
515
            }
516
        }
517
        catch (MetacatException me) {
518
            fail("Metacat Error:\n" + me.getMessage());
519
        }
520
        catch (Exception e) {
521
            fail("General exception:\n" + e.getMessage());
522
        }
523
    }
524

    
525
    /**
526
     * Read a document from metacat and check if it is equal to a given string.
527
     * The expected result is passed as result
528
     */
529

    
530
    private void readDocidWhichEqualsDoc(String docid, String testDoc,
531
                                         boolean result,
532
                                         boolean expextedKarmaFailure) {
533
        try {
534
            Reader r = m.read(docid);
535
            String doc = IOUtil.getAsString(r, true);
536
            if (result) {
537

    
538
                if (!testDoc.equals(doc)) {
539
                    System.out.println("doc    :" + doc);
540
                    System.out.println("testDoc:" + testDoc);
541
                }
542

    
543
                assertTrue(testDoc.equals(doc));
544
            }
545
            else {
546
                assertTrue(doc.indexOf("<error>") != -1);
547
            }
548
        }
549
        catch (MetacatInaccessibleException mie) {
550
            fail("Metacat Inaccessible:\n" + mie.getMessage());
551
        }
552
        catch (InsufficientKarmaException ike) {
553
            if (!expextedKarmaFailure) {
554
                fail("Insufficient karma:\n" + ike.getMessage());
555
            }
556
        }
557
        catch (MetacatException me) {
558
            fail("Metacat Error:\n" + me.getMessage());
559
        }
560
        catch (Exception e) {
561
            fail("General exception:\n" + e.getMessage());
562
        }
563

    
564
    }
565

    
566
    /**
567
     * Create a hopefully unique docid for testing insert and update. Does
568
     * not include the 'revision' part of the id.
569
     *
570
     * @return a String docid based on the current date and time
571
     */
572
    private String generateDocid() {
573
        StringBuffer docid = new StringBuffer(prefix);
574
        docid.append(".");
575

    
576
        // Create a calendar to get the date formatted properly
577
        String[] ids = TimeZone.getAvailableIDs( -8 * 60 * 60 * 1000);
578
        SimpleTimeZone pdt = new SimpleTimeZone( -8 * 60 * 60 * 1000, ids[0]);
579
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
580
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
581
                       2 * 60 * 60 * 1000);
582
        Calendar calendar = new GregorianCalendar(pdt);
583
        Date trialTime = new Date();
584
        calendar.setTime(trialTime);
585
        docid.append(calendar.get(Calendar.YEAR));
586
        docid.append(calendar.get(Calendar.DAY_OF_YEAR));
587
        docid.append(calendar.get(Calendar.HOUR_OF_DAY));
588
        docid.append(calendar.get(Calendar.MINUTE));
589
        docid.append(calendar.get(Calendar.SECOND));
590
   	    //sometimes this number is not unique, so we append a random number
591
    	int random = (new Double(Math.random()*100)).intValue();
592
    	docid.append(random);
593
        return docid.toString();
594
    }
595
}
(9-9/18)