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-05-15 18:25:04 -0700 (Thu, 15 May 2008) $'
9
 * '$Revision: 3875 $'
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 edu.ucsb.nceas.utilities.Options;
45
import junit.framework.Test;
46
import junit.framework.TestCase;
47
import junit.framework.TestSuite;
48
import java.io.File;
49

    
50
/**
51
 * A JUnit test for testing Metacat when Non Ascii Characters are inserted
52
 */
53
public class NonAsciiCharacterTest
54
    extends TestCase {
55
	 /* Initialize Options*/
56
    static
57
    {
58
  	  try
59
  	  {
60
  		  Options.initialize(new File("build/tests/metacat.properties"));
61
  		  MetaCatUtil.pathsForIndexing 
62
  		         = MetaCatUtil.getOptionList(MetaCatUtil.getOption("indexPaths"));
63
  	  }
64
  	  catch(Exception e)
65
  	  {
66
  		  System.err.println("Exception in initialize option in MetacatServletNetTest "+e.getMessage());
67
  	  }
68
    }
69
    private String metacatUrl = MetaCatUtil.getOption("metacatUrl");;
70
    private String username = MetaCatUtil.getOption("mcuser");
71
    private String password = MetaCatUtil.getOption("mcpassword");
72
    private String anotheruser = MetaCatUtil.getOption("mcanotheruser");
73
    private String anotherpassword = MetaCatUtil.getOption("mcanotherpassword");
74
    private String prefix = "test";
75
    private String newdocid = null;
76
    private String testdocument = "";
77

    
78
    private Metacat m;
79

    
80
    private boolean SUCCESS = true;
81
    private boolean FAILURE = false;
82

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

    
88
    private String testEml_Header =
89
        "<?xml version=\"1.0\"?><eml:eml" +
90
        " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"" +
91
        " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
92
        " packageId=\"eml.1.1\" system=\"knb\"" +
93
        " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\"" +
94
        " scope=\"system\">";
95

    
96
    private String testEmlCreatorBlock =
97
        "<creator scope=\"document\">                                       " +
98
        " <individualName>                                                  " +
99
        "    <surName>Smith</surName>                                       " +
100
        " </individualName>                                                 " +
101
        "</creator>                                                         ";
102

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

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

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

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

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

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

    
152
        return accessBlock;
153

    
154
    }
155

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

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

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

    
173
        return testDocument;
174
    }
175

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

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

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

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

    
219
        return suite;
220
    }
221

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

    
230

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

    
254

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

    
279

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

    
305

    
306

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

    
332

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

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

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

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

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

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

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

    
471
        return response;
472
    }
473

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

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

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

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

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

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

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

    
578
    }
579

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

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