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: tao $'
8
 *     '$Date: 2008-03-06 16:57:27 -0800 (Thu, 06 Mar 2008) $'
9
 * '$Revision: 3760 $'
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.client.InsufficientKarmaException;
37
import edu.ucsb.nceas.metacat.client.Metacat;
38
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
39
import edu.ucsb.nceas.metacat.client.MetacatException;
40
import edu.ucsb.nceas.metacat.client.MetacatFactory;
41
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
42
import edu.ucsb.nceas.utilities.IOUtil;
43
import junit.framework.Test;
44
import junit.framework.TestCase;
45
import junit.framework.TestSuite;
46
import java.io.File;
47

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

    
54
    private String metacatUrl = "@systemidserver@@servlet-path@";
55
    private String username = "@mcuser@";
56
    private String password = "@mcpassword@";
57
    private String anotheruser = "@mcanotheruser@";
58
    private String anotherpassword = "@mcanotherpassword@";
59
    private String prefix = "test";
60
    private String newdocid = null;
61
    private String testdocument = "";
62

    
63
    private Metacat m;
64

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

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

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

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

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

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

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

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

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

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

    
137
        return accessBlock;
138

    
139
    }
140

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

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

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

    
158
        return testDocument;
159
    }
160

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

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

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

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

    
204
        return suite;
205
    }
206

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

    
215

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

    
239

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

    
264

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

    
290

    
291

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

    
317

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

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

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

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

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

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

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

    
456
        return response;
457
    }
458

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

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

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

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

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

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

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

    
563
    }
564

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

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