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: 2007-11-06 14:43:04 -0800 (Tue, 06 Nov 2007) $'
9
 * '$Revision: 3584 $'
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; &amp; &lt;");
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, false);
275
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
276
            m.logout();
277
        }
278
        catch (MetacatAuthException mae) {
279
            fail("Authorization failed:\n" + mae.getMessage());
280
        }
281
        catch (MetacatInaccessibleException mie) {
282
            fail("Metacat Inaccessible:\n" + mie.getMessage());
283
        }
284
        catch (Exception e) {
285
            fail("General exception:\n" + e.getMessage());
286
        }
287
    }
288

    
289

    
290

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

    
315

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

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

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

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

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

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

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

    
454
        return response;
455
    }
456

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

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

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

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

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

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

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

    
561
    }
562

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

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