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-07-15 10:16:06 -0700 (Tue, 15 Jul 2008) $'
9
 * '$Revision: 4126 $'
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.metacat.service.PropertyService;
43
import edu.ucsb.nceas.metacat.util.SystemUtil;
44
import edu.ucsb.nceas.utilities.IOUtil;
45
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
46
import junit.framework.Test;
47
import junit.framework.TestCase;
48
import junit.framework.TestSuite;
49
import java.io.File;
50

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

    
57
    private static String metacatUrl;
58
    private static String username;
59
	private static String password;
60
	private static String anotheruser;
61
	private static String anotherpassword;
62
	static {
63
		try {
64
		    metacatUrl = SystemUtil.getServletURL();
65
			username = PropertyService.getProperty("test.mcuser");
66
			password = PropertyService.getProperty("test.mcpassword");
67
			anotheruser = PropertyService.getProperty("test.mcanotheruser");
68
			anotherpassword = PropertyService.getProperty("test.mcanotherpassword");
69
		} catch (PropertyNotFoundException pnfe) {
70
			System.err.println("Could not get property in static block: " 
71
					+ pnfe.getMessage());
72
		}
73
	}
74

    
75
    private String prefix = "test";
76
    private String newdocid = null;
77
    private String testdocument = "";
78

    
79
    private Metacat m;
80

    
81
    private boolean SUCCESS = true;
82
    private boolean FAILURE = false;
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_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 testEmlCreatorBlock =
98
        "<creator scope=\"document\">                                       " +
99
        " <individualName>                                                  " +
100
        "    <surName>Smith</surName>                                       " +
101
        " </individualName>                                                 " +
102
        "</creator>                                                         ";
103

    
104
    private String testEmlContactBlock =
105
        "<contact scope=\"document\">                                       " +
106
        " <individualName>                                                  " +
107
        "    <surName>Jackson</surName>                                     " +
108
        " </individualName>                                                 " +
109
        "</contact>                                                         ";
110

    
111
    /**
112
     * This function returns an access block based on the params passed
113
     */
114
    private String getAccessBlock(String principal, boolean grantAccess,
115
                                  boolean read, boolean write,
116
                                  boolean changePermission, boolean all) {
117
        String accessBlock = "<access " +
118
            "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\"" +
119
            " order=\"allowFirst\" scope=\"document\">";
120

    
121
        if (grantAccess) {
122
            accessBlock += "<allow>";
123
        }
124
        else {
125
            accessBlock += "<deny>";
126
        }
127

    
128
        accessBlock = accessBlock + "<principal>" + principal + "</principal>";
129

    
130
        if (all) {
131
            accessBlock += "<permission>all</permission>";
132
        }
133
        else {
134
            if (read) {
135
                accessBlock += "<permission>read</permission>";
136
            }
137
            if (write) {
138
                accessBlock += "<permission>write</permission>";
139
            }
140
            if (changePermission) {
141
                accessBlock += "<permission>changePermission</permission>";
142
            }
143
        }
144

    
145
        if (grantAccess) {
146
            accessBlock += "</allow>";
147
        }
148
        else {
149
            accessBlock += "</deny>";
150
        }
151
        accessBlock += "</access>";
152

    
153
        return accessBlock;
154

    
155
    }
156

    
157
    /**
158
     * This function returns a valid eml document with no access rules
159
     * This function is for eml-2.0.1 only. For other eml versions,
160
     * this function might have to modified
161
     */
162
    private String getTestEmlDoc(String title) {
163

    
164
        String testDocument = "";
165
        testDocument = testDocument + testEml_Header +
166
            "<dataset scope=\"document\"><title>" + title + "</title>" +
167
            testEmlCreatorBlock;
168

    
169
        testDocument += testEmlContactBlock;
170
        testDocument += getAccessBlock("public", true, true, false, false, false);
171
        testDocument += "</dataset>";
172
        testDocument += "</eml:eml>";
173

    
174
        return testDocument;
175
    }
176

    
177
    /**
178
     * Constructor to build the test
179
     *
180
     * @param name the name of the test method
181
     */
182
    public NonAsciiCharacterTest(String name) {
183
        super(name);
184
        newdocid = generateDocid();
185
    }
186

    
187
    /**
188
     * Establish a testing framework by initializing appropriate objects
189
     */
190
    public void setUp() {
191
        try {
192
            System.err.println("Test Metacat: " + metacatUrl);
193
            m = MetacatFactory.createMetacatConnection(metacatUrl);
194
        }
195
        catch (MetacatInaccessibleException mie) {
196
            System.err.println("Metacat is: " + metacatUrl);
197
            fail("Metacat connection failed." + mie.getMessage());
198
        }
199
    }
200

    
201
    /**
202
     * Release any objects after tests are complete
203
     */
204
    public void tearDown() {
205
    }
206

    
207
    /**
208
     * Create a suite of tests to be run together
209
     */
210
    public static Test suite() {
211
        TestSuite suite = new TestSuite();
212
        suite.addTest(new NonAsciiCharacterTest("initialize"));
213
        // Test basic functions
214
        suite.addTest(new NonAsciiCharacterTest("invalidXMLCharactersTest"));
215
        suite.addTest(new NonAsciiCharacterTest("symbolEncodedFormatTest"));
216
        suite.addTest(new NonAsciiCharacterTest("quoteTest"));
217
        suite.addTest(new NonAsciiCharacterTest("numericCharacterReferenceFormatTest"));
218
        suite.addTest(new NonAsciiCharacterTest("nonLatinUnicodeCharacterTest"));
219

    
220
        return suite;
221
    }
222

    
223
    /**
224
     * Run an initial test that always passes to check that the test
225
     * harness is working.
226
     */
227
    public void initialize() {
228
        assertTrue(1 == 1);
229
    }
230

    
231

    
232
    /** *********
233
     * Test inserting document with > & <
234
     * should fail because this means an invalid xml document is being inserted
235
     */
236
    public void invalidXMLCharactersTest() {
237
        try {
238
            newdocid = generateDocid();
239
            m.login(username, password);
240
            testdocument = getTestEmlDoc("Checking > & <");
241
            insertDocid(newdocid + ".1", testdocument, FAILURE, true);
242
            m.logout();
243
        }
244
        catch (MetacatAuthException mae) {
245
            fail("Authorization failed:\n" + mae.getMessage());
246
        }
247
        catch (MetacatInaccessibleException mie) {
248
            fail("Metacat Inaccessible:\n" + mie.getMessage());
249
        }
250
        catch (Exception e) {
251
            fail("General exception:\n" + e.getMessage());
252
        }
253
    }
254

    
255

    
256
    /** *********
257
     * Test inserting document with &gt; &amp; &lt;
258
     * should fail because this means an invalid xml document is being inserted
259
     */
260
    public void symbolEncodedFormatTest() {
261
        try {
262
            newdocid = generateDocid();
263
            m.login(username, password);
264
            testdocument = getTestEmlDoc("Checking &gt; &lt; &quot; &apos; &amp;");
265
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
266
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, false);
267
            m.logout();
268
        }
269
        catch (MetacatAuthException mae) {
270
            fail("Authorization failed:\n" + mae.getMessage());
271
        }
272
        catch (MetacatInaccessibleException mie) {
273
            fail("Metacat Inaccessible:\n" + mie.getMessage());
274
        }
275
        catch (Exception e) {
276
            fail("General exception:\n" + e.getMessage());
277
        }
278
    }
279

    
280

    
281
    /** *********
282
     * Test inserting document with single quote and double quote
283
     * should fail because this means an invalid xml document is being inserted
284
     */
285
    public void quoteTest() {
286
        try {
287
            newdocid = generateDocid();
288
            m.login(username, password);
289
            testdocument = getTestEmlDoc("Checking ' ` \"");
290
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
291
            testdocument = getTestEmlDoc("Checking &apos; ` &quot;");
292
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
293
            m.logout();
294
        }
295
        catch (MetacatAuthException mae) {
296
            fail("Authorization failed:\n" + mae.getMessage());
297
        }
298
        catch (MetacatInaccessibleException mie) {
299
            fail("Metacat Inaccessible:\n" + mie.getMessage());
300
        }
301
        catch (Exception e) {
302
            fail("General exception:\n" + e.getMessage());
303
        }
304
    }
305

    
306

    
307

    
308
    /** *********
309
     * Test inserting document with micro sign
310
     * should fail because this means an invalid xml document is being inserted
311
     */
312
    public void numericCharacterReferenceFormatTest() {
313
        try {
314
            newdocid = generateDocid();
315
            m.login(username, password);
316
            testdocument = getTestEmlDoc("Checking &#181;");
317
            insertDocid(newdocid + ".1", testdocument, SUCCESS, true);
318
            testdocument = getTestEmlDoc("Checking µ");
319
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
320
            m.logout();
321
        }
322
        catch (MetacatAuthException mae) {
323
            fail("Authorization failed:\n" + mae.getMessage());
324
        }
325
        catch (MetacatInaccessibleException mie) {
326
            fail("Metacat Inaccessible:\n" + mie.getMessage());
327
        }
328
        catch (Exception e) {
329
            fail("General exception:\n" + e.getMessage());
330
        }
331
    }
332

    
333

    
334
    /** *********
335
     * Test inserting document with characters like µ
336
     * should fail because this means an invalid xml document is being inserted
337
     */
338
    public void nonLatinUnicodeCharacterTest() {
339
        try {
340
            newdocid = generateDocid();
341
            m.login(username, password);
342
            testdocument = getTestEmlDoc("Checking charcters like µ");
343
            insertDocid(newdocid + ".1", testdocument, SUCCESS, false);
344
            //testdocument = getTestEmlDoc("Checking charcters like &#181;");
345
            readDocidWhichEqualsDoc(newdocid, testdocument, SUCCESS, true);
346
            m.logout();
347
        }
348
        catch (MetacatAuthException mae) {
349
            fail("Authorization failed:\n" + mae.getMessage());
350
        }
351
        catch (MetacatInaccessibleException mie) {
352
            fail("Metacat Inaccessible:\n" + mie.getMessage());
353
        }
354
        catch (Exception e) {
355
            fail("General exception:\n" + e.getMessage());
356
        }
357
    }
358

    
359
    /**
360
     * Insert a document into metacat. The expected result is passed as result
361
     */
362

    
363
    private String insertDocid(String docid, String docText, boolean result,
364
                               boolean expectMetacatException) {
365
        String response = null;
366
        try {
367
            response = m.insert(docid,
368
                                new StringReader(docText), null);
369
            System.err.println(response);
370
            if (result) {
371
                assertTrue( (response.indexOf("<success>") != -1));
372
                assertTrue(response.indexOf(docid) != -1);
373
            }
374
            else {
375
                assertTrue( (response.indexOf("<success>") == -1));
376
            }
377
        }
378
        catch (MetacatInaccessibleException mie) {
379
            fail("Metacat Inaccessible:\n" + mie.getMessage());
380
        }
381
        catch (InsufficientKarmaException ike) {
382
                fail("Insufficient karma:\n" + ike.getMessage());
383
        }
384
        catch (MetacatException me) {
385
            if (!expectMetacatException) {
386
                fail("Metacat Error:\n" + me.getMessage());
387
            }
388
        }
389
        catch (Exception e) {
390
            fail("General exception:\n" + e.getMessage());
391
        }
392
        return response;
393
    }
394

    
395
    /**
396
     * Insert a document into metacat. The expected result is passed as result
397
     */
398

    
399
    private String uploadDocid(String docid, String filePath, boolean result,
400
                               boolean expectedKarmaException) {
401
        String response = null;
402
        try {
403
            response = m.upload(docid, new File(filePath));
404
            if (result) {
405
                assertTrue( (response.indexOf("<success>") != -1));
406
                assertTrue(response.indexOf(docid) != -1);
407
            }
408
            else {
409
                assertTrue( (response.indexOf("<success>") == -1));
410
            }
411
            System.err.println("respose from metacat: " + response);
412
        }
413
        catch (MetacatInaccessibleException mie) {
414
            fail("Metacat Inaccessible:\n" + mie.getMessage());
415
        }
416
        catch (InsufficientKarmaException ike) {
417
            if (!expectedKarmaException) {
418
                fail("Insufficient karma:\n" + ike.getMessage());
419
            }
420
        }
421
        catch (MetacatException me) {
422
            if (result) {
423
                fail("Metacat Error:\n" + me.getMessage());
424
            } else {
425
                System.err.println("Metacat Error:\n" + me.getMessage());
426
            }
427
        }
428
        catch (Exception e) {
429
            fail("General exception:\n" + e.getMessage());
430
        }
431
        return response;
432
    }
433

    
434
    /**
435
     * Update a document in metacat. The expected result is passed as result
436
     */
437
    private String updateDocid(String docid, String docText, boolean result,
438
                               boolean expectedKarmaFailure) {
439
        String response = null;
440
        try {
441
            response = m.update(docid,
442
                                new StringReader(testdocument), null);
443

    
444
            if (result) {
445
                assertTrue( (response.indexOf("<success>") != -1));
446
                assertTrue(response.indexOf(docid) != -1);
447
            }
448
            else {
449
                assertTrue( (response.indexOf("<success>") == -1));
450
            }
451
            System.err.println(response);
452
        }
453
        catch (MetacatInaccessibleException mie) {
454
            fail("Metacat Inaccessible:\n" + mie.getMessage());
455
        }
456
        catch (InsufficientKarmaException ike) {
457
            if (!expectedKarmaFailure) {
458
                fail("Insufficient karma:\n" + ike.getMessage());
459
            }
460
        }
461
        catch (MetacatException me) {
462
            if (result) {
463
                fail("Metacat Error:\n" + me.getMessage());
464
            } else {
465
                System.err.println("Metacat Error:\n" + me.getMessage());
466
            }
467
        }
468
        catch (Exception e) {
469
            fail("General exception:\n" + e.getMessage());
470
        }
471

    
472
        return response;
473
    }
474

    
475
    /**
476
     * Delete a document into metacat. The expected result is passed as result
477
     */
478
    private void deleteDocid(String docid, boolean result,
479
                             boolean expextedKarmaFailure) {
480
        try {
481
            String response = m.delete(docid);
482
            if (result) {
483
                assertTrue(response.indexOf("<success>") != -1);
484
            }
485
            else {
486
                assertTrue(response.indexOf("<success>") == -1);
487
            }
488
            System.err.println(response);
489
        }
490
        catch (MetacatInaccessibleException mie) {
491
            fail("Metacat Inaccessible:\n" + mie.getMessage());
492
        }
493
        catch (InsufficientKarmaException ike) {
494
            if(!expextedKarmaFailure){
495
                fail("Insufficient karma:\n" + ike.getMessage());
496
            }
497
        }
498
        catch (MetacatException me) {
499
            if (result) {
500
                fail("Metacat Error:\n" + me.getMessage());
501
            } else {
502
                System.err.println("Metacat Error:\n" + me.getMessage());
503
            }
504
        }
505
        catch (Exception e) {
506
            fail("General exception:\n" + e.getMessage());
507
        }
508
    }
509

    
510
    /**
511
     * Read a document from metacat. The expected result is passed as result
512
     */
513
    private void readDocid(String docid, boolean result,
514
                           boolean expextedKarmaFailure) {
515
        try {
516
            Reader r = m.read(docid);
517
            String response = IOUtil.getAsString(r, true);
518

    
519
            if (!result) {
520
                assertTrue(response.indexOf("<success>") == -1);
521
            }
522
            // System.err.println(response);
523
        }
524
        catch (MetacatInaccessibleException mie) {
525
            fail("Metacat Inaccessible:\n" + mie.getMessage());
526
        }
527
        catch (InsufficientKarmaException ike) {
528
            if (!expextedKarmaFailure) {
529
                fail("Insufficient karma:\n" + ike.getMessage());
530
            }
531
        }
532
        catch (MetacatException me) {
533
            fail("Metacat Error:\n" + me.getMessage());
534
        }
535
        catch (Exception e) {
536
            fail("General exception:\n" + e.getMessage());
537
        }
538
    }
539

    
540
    /**
541
     * Read a document from metacat and check if it is equal to a given string.
542
     * The expected result is passed as result
543
     */
544

    
545
    private void readDocidWhichEqualsDoc(String docid, String testDoc,
546
                                         boolean result,
547
                                         boolean expextedKarmaFailure) {
548
        try {
549
            Reader r = m.read(docid);
550
            String doc = IOUtil.getAsString(r, true);
551
            if (result) {
552

    
553
                if (!testDoc.equals(doc)) {
554
                    System.out.println("doc    :" + doc);
555
                    System.out.println("testDoc:" + testDoc);
556
                }
557

    
558
                assertTrue(testDoc.equals(doc));
559
            }
560
            else {
561
                assertTrue(doc.indexOf("<error>") != -1);
562
            }
563
        }
564
        catch (MetacatInaccessibleException mie) {
565
            fail("Metacat Inaccessible:\n" + mie.getMessage());
566
        }
567
        catch (InsufficientKarmaException ike) {
568
            if (!expextedKarmaFailure) {
569
                fail("Insufficient karma:\n" + ike.getMessage());
570
            }
571
        }
572
        catch (MetacatException me) {
573
            fail("Metacat Error:\n" + me.getMessage());
574
        }
575
        catch (Exception e) {
576
            fail("General exception:\n" + e.getMessage());
577
        }
578

    
579
    }
580

    
581
    /**
582
     * Create a hopefully unique docid for testing insert and update. Does
583
     * not include the 'revision' part of the id.
584
     *
585
     * @return a String docid based on the current date and time
586
     */
587
    private String generateDocid() {
588
        StringBuffer docid = new StringBuffer(prefix);
589
        docid.append(".");
590

    
591
        // Create a calendar to get the date formatted properly
592
        String[] ids = TimeZone.getAvailableIDs( -8 * 60 * 60 * 1000);
593
        SimpleTimeZone pdt = new SimpleTimeZone( -8 * 60 * 60 * 1000, ids[0]);
594
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
595
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY,
596
                       2 * 60 * 60 * 1000);
597
        Calendar calendar = new GregorianCalendar(pdt);
598
        Date trialTime = new Date();
599
        calendar.setTime(trialTime);
600
        docid.append(calendar.get(Calendar.YEAR));
601
        docid.append(calendar.get(Calendar.DAY_OF_YEAR));
602
        docid.append(calendar.get(Calendar.HOUR_OF_DAY));
603
        docid.append(calendar.get(Calendar.MINUTE));
604
        docid.append(calendar.get(Calendar.SECOND));
605
   	    //sometimes this number is not unique, so we append a random number
606
    	int random = (new Double(Math.random()*100)).intValue();
607
    	docid.append(random);
608
        return docid.toString();
609
    }
610
}
(9-9/18)