Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2010 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: berkley $'
8
 *     '$Date: 2010-05-03 14:26:08 -0700 (Fri, 14 Aug 2009) $'
9
 * '$Revision: 5027 $'
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.metacat.dataone;
27

    
28
import java.util.*;
29
import java.io.*;
30

    
31
import java.security.MessageDigest;
32

    
33
import edu.ucsb.nceas.MCTestCase;
34
import edu.ucsb.nceas.metacat.IdentifierManager;
35
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
36
import edu.ucsb.nceas.metacat.client.MetacatException;
37
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
38
import edu.ucsb.nceas.metacat.dataone.CrudService;
39
import junit.framework.Test;
40
import junit.framework.TestSuite;
41

    
42
import org.apache.log.LogEvent;
43
import org.dataone.service.exceptions.InvalidRequest;
44
import org.dataone.service.exceptions.InvalidToken;
45
import org.dataone.service.exceptions.NotAuthorized;
46
import org.dataone.service.exceptions.NotImplemented;
47
import org.dataone.service.exceptions.ServiceFailure;
48
import org.dataone.service.types.*;
49

    
50
import edu.ucsb.nceas.metacat.properties.PropertyService;
51
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
52

    
53
import edu.ucsb.nceas.metacat.service.SessionService;
54
import edu.ucsb.nceas.metacat.util.SessionData;
55

    
56
import com.gc.iotools.stream.is.InputStreamFromOutputStream;
57

    
58
/**
59
 * A JUnit test for testing the dataone CrudService class
60
 */
61
public class CrudServiceTest extends MCTestCase 
62
{   
63
    /**
64
    * consstructor for the test
65
    */
66
    public CrudServiceTest(String name)
67
    {
68
        super(name);
69
    }
70
  
71
    /**
72
	 * Establish a testing framework by initializing appropriate objects
73
	 */
74
	public void setUp() throws Exception 
75
	{
76
		super.setUp();
77
	}
78

    
79
	/**
80
	 * Release any objects after tests are complete
81
	 */
82
	public void tearDown() 
83
	{
84
	}
85

    
86
	/**
87
	 * Create a suite of tests to be run together
88
	 */
89
	public static Test suite() 
90
	{
91
		TestSuite suite = new TestSuite();
92
		suite.addTest(new CrudServiceTest("initialize"));
93
		suite.addTest(new CrudServiceTest("testSingletonAccessor"));
94
		suite.addTest(new CrudServiceTest("testCreateAndGet"));
95
		suite.addTest(new CrudServiceTest("testGetSystemMetadata"));
96
		suite.addTest(new CrudServiceTest("testUpdate"));
97
		suite.addTest(new CrudServiceTest("testListObjects"));
98
		suite.addTest(new CrudServiceTest("testAccessControl"));
99
		suite.addTest(new CrudServiceTest("testGenerateMissingSystemMetadata"));
100
		suite.addTest(new CrudServiceTest("testGetLogRecords"));
101
		suite.addTest(new CrudServiceTest("testChecksumError"));
102
		suite.addTest(new CrudServiceTest("testPublicAccess"));
103
		suite.addTest(new CrudServiceTest("testFailedCreate"));
104
		return suite;
105
	}
106
	
107
	/**
108
	 * insert an invalid document and make sure create fails and does not
109
	 * leave any artifacts behind
110
	 */
111
	public void testFailedCreate()
112
	{
113
	    try
114
	    {
115
	        String invalidDoc = "<xxx></yyy>";
116
	        System.out.println("trying to insert doc " + invalidDoc);
117
	        CrudService cs = CrudService.getInstance();
118
            AuthToken token = getToken();
119
            //run create
120
            try
121
            {
122
                Identifier id = createDoc(token, invalidDoc);
123
                fail("Should have thrown an exception.");
124
            }
125
            catch(Exception e)
126
            {
127
                //e.printStackTrace();
128
            }
129
            
130
	    }
131
	    catch(Exception e)
132
	    {
133
	        fail("unexpected exception in testFailedCreate: " + e.getMessage());
134
	    }
135
	}
136
	
137
	/**
138
	 * test to make sure that get and listObjects methods are publicly accessible
139
	 */
140
	public void testPublicAccess()
141
	{
142
	    try
143
	    {
144
	        AuthToken token = new AuthToken("public");
145
	        //AuthToken token = getToken();
146
	        CrudService cs = CrudService.getInstance();
147
	        ObjectList ol = cs.listObjects(token, null, null, null);
148
	        System.out.println("ol: " + ol.sizeObjectInfoList());
149
	        assertTrue(ol.sizeObjectInfoList() > 0);
150
	        
151
	        ObjectInfo oi = ol.getObjectInfo(0);
152
	        String s = getDoc(token, oi.getIdentifier());
153
	        assertNotNull(s);
154
	        
155
	        try
156
	        { //try a create with the public auth.  should fail
157
	            Identifier id = new Identifier();
158
	            String docid = generateDocumentId();
159
	            id.setValue(docid);
160
	            String testDoc = getTestDoc();
161
	            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
162
	            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
163
	            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
164
	            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
165
	            //create the doc
166
	            Identifier idC = cs.create(token, id, sbis, sm);
167
	            fail("Should have thrown an auth exception");
168
	        }
169
	        catch(Exception e)
170
	        {
171
	            
172
	        }
173
	        
174
	        //create a legit doc
175
	        token = getToken();
176
	        Identifier id = new Identifier();
177
            String docid = generateDocumentId();
178
            id.setValue(docid);
179
            String testDoc = getTestDoc();
180
            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
181
            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
182
            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
183
            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
184
            //create the doc
185
            Identifier idC = cs.create(token, id, sbis, sm);
186
            //make it public, then use a public token to try to get it
187
            InputStream data = null;
188
            try
189
            {
190
                AuthToken publicToken = new AuthToken("public");
191
                data = cs.get(publicToken, id);
192
                data.read();
193
                
194
                fail("should have thrown an exception");
195
            }
196
            catch(Exception e)
197
            {
198
                /*System.out.println("%%%%%%%%%%%%%%%%%%%%%%%getting result");
199
                Object o = ((InputStreamFromOutputStream)data).getResult();
200
                System.out.println("result: " + o);
201
                System.out.println("exception thrown!");
202
                System.out.println("exception thrown: " + e.getClass().getName());*/
203
            }
204
            
205
            
206
            
207
            makeDocPublic(token, id, true);
208
            token = new AuthToken("public");
209
	        data = cs.get(token, id);
210
	    }
211
	    catch(Exception e)
212
	    {
213
	        fail("Error in testPublicAccess: " + e.getMessage());
214
	    }
215
	    
216
	}
217
	
218
	/**
219
	 * test for an error where the checksum algorithm gets appended onto the checksum.
220
	 */
221
	public void testChecksumError()
222
	{
223
	    printTestHeader("testChecksumError");
224
	    try
225
	    {
226
	        Date d1 = new Date();
227
	        CrudService cs = CrudService.getInstance();
228
	        AuthToken token = getToken();
229
	        ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
230
	        //create docs at different times
231

    
232
	        Identifier id = new Identifier();
233
	        String docid = generateDocumentId();
234
	        id.setValue(docid);
235

    
236
	        //create the system metadata then run the create method
237
	        String testDoc = getTestDoc();
238
	        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
239
	        SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
240
	        assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
241
	        //create the doc
242
	        Identifier idC = cs.create(token, id, sbis, sm);
243
	        assertTrue(idC.getValue().equals(id.getValue()));
244
	        SystemMetadata smC = getSystemMetadata(token, idC);
245
	        assertFalse(smC.getChecksum().getValue().startsWith("MD5"));
246
	        
247
	        Date d2 = new Date();
248
	        ObjectList ol = cs.listObjects(token, d1, d2, of1);
249
	        assertTrue(ol.sizeObjectInfoList() > 0);
250
	        ObjectInfo oi = ol.getObjectInfo(0);
251
	        //this will fail if the error state exists.
252
	        assertFalse(oi.getChecksum().getValue().startsWith("MD5"));
253
	    }
254
	    catch(Exception e)
255
	    {
256
	        fail("Unexpected exception: " + e.getMessage());
257
	    }
258
        
259
	}
260
	
261
	/**
262
	 * test CrudService.getLogRecords
263
	 */
264
	public void testGetLogRecords()
265
	{
266
	    printTestHeader("testGetLogRecords");
267
	    try
268
	    {
269
	        CrudService cs = CrudService.getInstance();
270
	        AuthToken token = getToken();
271
	        Date fromDate = new Date();
272
	        Identifier id = createDoc(token, getTestDoc());
273
	        Date toDate = new Date();
274
	        Log lrs = cs.getLogRecords(token, fromDate, toDate, null);
275
	        assertNotNull(lrs);
276
	        assertTrue(lrs.sizeLogEntryList() == 1);
277
	        LogEntry lrLogEvent = lrs.getLogEntry(0);
278
	        assertTrue(lrLogEvent.getEvent().name().equals("CREATE"));
279
	        assertTrue(lrLogEvent.getIdentifier().getValue().equals(id.getValue()));
280
	    }
281
	    catch(Exception e)
282
	    {
283
	        e.printStackTrace();
284
	        fail("testGetLogRecords threw an unexpected exception: " + e.getMessage());
285
	    }
286
	}
287
	
288
	/**
289
	 * test the generation of system metadata for docs that don't already 
290
	 * have it.  This will be used for migration of existing object stores
291
	 * to dataone.
292
	 */
293
	public void testGenerateMissingSystemMetadata()
294
	{
295
	    printTestHeader("testGenerateMissingSystemMetadata");
296
	    try
297
	    {
298
	        CrudService cs = CrudService.getInstance();
299
	        AuthToken token = getToken();
300
	        //create a document with no system metadata
301
	        String testDoc = getTestDoc();
302
	        Identifier id = new Identifier();
303
	        String docid = generateDocumentId();
304
	        id.setValue(docid);
305
	        
306
	        cs.insertOrUpdateDocument(testDoc, id, cs.getSessionData(token), "insert", false); 
307
	        //try to get its system metadata, should fail
308
	        try
309
	        {
310
	            getSystemMetadata(token, id);
311
	            fail("call to getSystemMetadata should have failed.");
312
	        }
313
	        catch(Exception e)
314
	        {}
315
	        
316
	        //generate missing system metadata
317
	        cs.generateMissingSystemMetadata(token);
318
	        //try to get system metadata again, should succeed
319
	        getSystemMetadata(token, id);
320
	    }
321
	    catch(Exception e)
322
	    {
323
	        fail("Unexpected error generating missing system metadata: " + e.getMessage());
324
	    }
325
	}
326
	
327
	/**
328
	 * make sure that only valid sessions can update/delete
329
	 */
330
	public void testAccessControl()
331
	{
332
	    printTestHeader("testAccessControl");
333
        try
334
        {
335
            CrudService cs = CrudService.getInstance();
336
            AuthToken token = getToken();
337
            //create a doc
338
            Identifier id = createDoc(token, getTestDoc());
339
            
340
            //get the doc and sysmetadata
341
            String gotDoc = getDoc(token, id);
342
            SystemMetadata sm = getSystemMetadata(token, id);
343
            
344
            //break the session id
345
            String sessionid = "somefakesessionid";
346
            token = new AuthToken(sessionid);
347
            
348
            //update the doc
349
            gotDoc = gotDoc.replaceAll("XXX", "YYY");
350
            Identifier newid = new Identifier();
351
            newid.setValue(generateDocumentId());
352
            StringBufferInputStream sbis = new StringBufferInputStream(gotDoc);
353
            SystemMetadata newsm = createSystemMetadata(newid, gotDoc);
354
            Identifier updatedid = cs.update(token, newid, sbis, id, newsm);
355
            fail("exception should have been thrown.");
356
        }
357
        catch(Exception e)
358
        {
359
        }
360
        
361
        try
362
        {
363
            CrudService cs = CrudService.getInstance();
364
            AuthToken token = new AuthToken("somefakesessionid");
365
            //create a doc
366
            Identifier id = createDoc(token, getTestDoc());
367
            fail("exception should have been thrown.");
368
        }
369
        catch(Exception e)
370
        {
371
        }
372
	}
373
	
374
	/**
375
	 * public ObjectList listObjects(AuthToken token, Date startTime, Date endTime, 
376
     *     ObjectFormat objectFormat, boolean replicaStatus, int start, int count)
377
     *       throws NotAuthorized, InvalidRequest, NotImplemented, ServiceFailure, InvalidToken
378
	 */
379
	public void testListObjects()
380
	{
381
	    printTestHeader("testListObjects");
382
	    try
383
	    {
384
	        CrudService cs = CrudService.getInstance();
385
	        AuthToken token = getToken();
386
	        ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
387
	        ObjectFormat of2 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.0.0");
388
	        //create docs at different times
389
	        Date d1 = new Date();
390
	        Identifier id1 = createDoc(token, getTestDoc(), of1);
391
            SystemMetadata sm1 = getSystemMetadata(token, id1);
392
            
393
            Date d2 = new Date();
394
            Identifier id2 = createDoc(token, getTestDoc(), of2);
395
            makeDocPublic(token, id2, true);
396
            SystemMetadata sm2 = getSystemMetadata(token, id2);
397
            
398
            Date d3 = new Date();
399
            Identifier id3 = createDoc(token, getTestDoc(), of1);
400
            makeDocPublic(token, id3, true);
401
            SystemMetadata sm3 = getSystemMetadata(token, id3);
402
              
403
            Date d4 = new Date();
404
            Identifier id4 = createDoc(token, getTestDoc(), of2);
405
            makeDocPublic(token, id4, true);
406
            SystemMetadata sm4 = getSystemMetadata(token, id4);
407
            
408
            Date d5 = new Date();
409
            Identifier id5 = createDoc(token, getTestDoc(), of1);
410
            makeDocPublic(token, id5, true);
411
            SystemMetadata sm5 = getSystemMetadata(token, id5);  
412
             
413
            Date d6 = new Date();
414
            
415
            //now get the objects for specific time ranges and test that it returns
416
            //the correct objects
417
            
418
            //ObjectList list = cs.listObjects(token, null, null, null);
419
            //System.out.println("list size: " + list.sizeObjectInfoList());
420
           
421
            //should return sm1 and sm2
422
            ObjectList list1 = cs.listObjects(token, d1, d3, null);
423
            assertTrue(list1.sizeObjectInfoList() == 2);
424
            assertTrue(idInObjectList(id1, list1));
425
            assertTrue(idInObjectList(id2, list1));
426
            
427
            ObjectInfo info = list1.getObjectInfo(0);
428
            
429
            
430
            //should only return sm1
431
            ObjectList list2 = cs.listObjects(token, d1, d3, of1);
432
            assertTrue(list2.sizeObjectInfoList() == 1);
433
            assertTrue(idInObjectList(id1, list2));
434
            
435
            //should return sm1-sm4
436
            ObjectList list3 = cs.listObjects(token, d1, d5, null);
437
            assertTrue(list3.sizeObjectInfoList() == 4);
438
            ObjectInfo oi4 = list3.getObjectInfo(0);
439
            assertTrue(idInObjectList(id1, list3));
440
            assertTrue(idInObjectList(id2, list3));
441
            assertTrue(idInObjectList(id3, list3));
442
            assertTrue(idInObjectList(id4, list3));
443
            
444
            //should only return sm2 and sm4
445
            ObjectList list4 = cs.listObjects(token, d1, d5, of2);
446
            assertTrue(list4.sizeObjectInfoList() == 2);
447
            assertTrue(idInObjectList(id2, list4));
448
            assertTrue(idInObjectList(id4, list4));
449
            
450
            //should return all
451
            ObjectList list5 = cs.listObjects(token, d1, d6, null);
452
            assertTrue(list5.sizeObjectInfoList() == 5);
453
            assertTrue(idInObjectList(id1, list5));
454
            assertTrue(idInObjectList(id2, list5));
455
            assertTrue(idInObjectList(id3, list5));
456
            assertTrue(idInObjectList(id4, list5));
457
            assertTrue(idInObjectList(id5, list5));
458
            
459
            //should return 1, 3, 5
460
            ObjectList list6 = cs.listObjects(token, d1, d6, of1);
461
            assertTrue(list6.sizeObjectInfoList() == 3);
462
            assertTrue(idInObjectList(id1, list6));
463
            assertTrue(idInObjectList(id3, list6));
464
            assertTrue(idInObjectList(id5, list6));
465
            
466
            //should return 4 (id1 is not public)
467
            token = new AuthToken("public");
468
            ObjectList list7 = cs.listObjects(token, d1, d6, null);
469
            //System.out.println("list7 size: " + list7.sizeObjectInfoList());
470
            assertTrue(list7.sizeObjectInfoList() == 4);
471
            
472
            //test paging
473
            ObjectList list8 = cs.listObjects(token, d1, d6, null, false, 2, 2);
474
            assertTrue(list8.getCount() == 2);
475
            assertTrue(list8.getStart() == 2);
476
            assertTrue(list8.getTotal() == 4);
477
            
478
	    }
479
	    catch(Exception e)
480
	    {
481
	        //e.printStackTrace();
482
	        fail("Error in listObjects: " + e.getMessage());
483
	    }
484
	}
485
	
486
	private boolean idInObjectList(Identifier id, ObjectList list)
487
	{
488
	    for(int i=0; i<list.sizeObjectInfoList(); i++)
489
	    {
490
	        ObjectInfo oi = list.getObjectInfo(i);
491
	        if(id.getValue().equals(oi.getIdentifier().getValue()))
492
	            return true;
493
	    }
494
	    return false;
495
	}
496
	
497
	/**
498
	 * public Identifier update(AuthToken token, Identifier guid, 
499
     *       InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
500
     *         throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
501
     *           UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
502
     *           NotImplemented
503
	 */
504
	public void testUpdate()
505
	{
506
	    printTestHeader("testUpdate");
507
	    try
508
	    {
509
	        CrudService cs = CrudService.getInstance();
510
	        AuthToken token = getToken();
511
            //create a doc
512
            Identifier id = createDoc(token, getTestDoc());
513
            
514
            //get the doc and sysmetadata
515
            String gotDoc = getDoc(token, id);
516
            SystemMetadata sm = getSystemMetadata(token, id);
517
            
518
            //update the doc
519
            gotDoc = gotDoc.replaceAll("XXX", "YYY");
520
            Identifier newid = new Identifier();
521
            newid.setValue(generateDocumentId());
522
            StringBufferInputStream sbis = new StringBufferInputStream(gotDoc);
523
            SystemMetadata newsm = createSystemMetadata(newid, gotDoc);
524
            Identifier updatedid = cs.update(token, newid, sbis, id, newsm);
525
            
526
            //get doc - check that it matches update
527
            String newdoc = getDoc(token, newid);
528
            assertTrue(gotDoc.equals(newdoc));
529
            
530
            //get sysmeta - check that ids and other fields are updated
531
            SystemMetadata newnewsm = getSystemMetadata(token, id);
532
            assertTrue(newnewsm.getObsoletedBy(0).getValue().equals(newid.getValue()));
533
            
534
            //get the new sysmeta and make sure the obsoletes field is set
535
            SystemMetadata newnewnewsm = getSystemMetadata(token, newid);
536
            assertTrue(newnewnewsm.getObsolete(0).getValue().equals(id.getValue()));
537
        }
538
        catch(Exception e)
539
        {
540
            e.printStackTrace();
541
            fail("Error in testUpdate: " + e.getMessage());
542
        }
543
	}
544
	
545
	/**
546
	 * public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
547
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
548
     *       InvalidRequest, NotImplemented
549
	 */
550
	public void testGetSystemMetadata()
551
	{
552
	    printTestHeader("testGetSystemMetadata");
553
	    try
554
	    {
555
            CrudService cs = CrudService.getInstance();
556
            AuthToken token = getToken();
557
            //run create
558
            Identifier id = createDoc(token, getTestDoc());
559
            //get the systemMetadata and make sure it is the correct object for this testDoc
560
            SystemMetadata sm = getSystemMetadata(token, id);
561
            assertTrue(sm.getIdentifier().getValue().equals(id.getValue()));
562
            assertTrue(sm.getChecksum().getValue().equals(checksum(getTestDoc())));
563
            
564
            try
565
            {
566
                Identifier fakeid = new Identifier();
567
                fakeid.setValue("somethingfake.234234");
568
                getSystemMetadata(token, fakeid);
569
                fail("getSystemMetadata should have thrown an exception.");
570
            }
571
            catch(Exception e)
572
            {
573
                assertTrue(true);
574
            }
575
        }
576
        catch(Exception e)
577
        {
578
            e.printStackTrace();
579
            fail("Error testing system metadata: " + e.getMessage());
580
        }
581
	}
582
	
583
	/**
584
	 * create(AuthToken token, Identifier guid, InputStream object, SystemMetadata sysmeta) 
585
     *   throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
586
     *       InsufficientResources, InvalidSystemMetadata, NotImplemented
587
     *
588
     * public InputStream get(AuthToken token, Identifier guid)
589
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
590
     *       NotImplemented
591
	 */
592
	public void testCreateAndGet()
593
	{
594
	    printTestHeader("testCreateAndGet");
595
	    try
596
	    {
597
	        CrudService cs = CrudService.getInstance();
598
	        AuthToken token = getToken();
599
	        //run create
600
	        Identifier id = createDoc(token, getTestDoc());
601
	        //make these docs public for debugging purposes.
602
	        makeDocPublic(token, id, true);
603
            //compare the docs
604
            String gotDoc = getDoc(token, id);
605
            assertTrue(gotDoc.trim().equals(getTestDoc().trim()));
606
            
607
            try
608
            {
609
                Identifier fakeid = new Identifier();
610
                fakeid.setValue("somethingfake.234234");
611
                getDoc(token, fakeid);
612
                fail("testCreateAndGet should have thrown an exception.");
613
            }
614
            catch(Exception e)
615
            {
616
                assertTrue(true);
617
            }
618
        }
619
        catch(Exception e)
620
        {
621
            e.printStackTrace();
622
            fail("Error in testCreate: " + e.getMessage());
623
        }
624
	}
625

    
626
	/**
627
	 * getInstance()
628
	 */
629
	public void testSingletonAccessor()
630
	{
631
	    printTestHeader("testSingletonAccessor");
632
	    CrudService cs = CrudService.getInstance();
633
	    assertNotNull(cs);
634
	}
635
	
636
	/**
637
	 * Run an initial test that always passes to check that the test harness is
638
	 * working.
639
	 */
640
	public void initialize() 
641
	{
642
	    printTestHeader("initialize");
643
		assertTrue(1 == 1);
644
	}
645
	
646
	/**
647
	 * return the systemMetadata object for id
648
	 */
649
	private SystemMetadata getSystemMetadata(AuthToken token, Identifier id)
650
	  throws Exception
651
	{
652
	    CrudService cs = CrudService.getInstance();
653
	    return cs.getSystemMetadata(token, id);
654
	}
655
	
656
	/**
657
	 * get a doc from metacat using CrudService.get()
658
	 */
659
	private String getDoc(AuthToken token, Identifier id)
660
	  throws Exception
661
	{
662
	    CrudService cs = CrudService.getInstance();
663
	    //try to get the same doc then compare them
664
        InputStream gotDocStream = cs.get(token, id);
665
        StringBuffer sb = new StringBuffer();
666
        byte[] b = new byte[1024];
667
        int numread = gotDocStream.read(b, 0, 1024);
668
        while(numread != -1)
669
        {
670
            sb.append(new String(b, 0, numread));
671
            numread = gotDocStream.read(b, 0, 1024);
672
        }
673
        return sb.toString();
674
	}
675
	
676
	/**
677
	 * return a test document
678
	 */
679
	private String getTestDoc()
680
	{
681
	    return "<?xml version=\"1.0\"?><test><somecontent>This is some content XXX</somecontent></test>\n";
682
	}
683
	
684
	/**
685
	 * authenticate and return a token
686
	 */
687
	private AuthToken getToken()
688
	  throws Exception
689
	{
690
	    CrudService cs = CrudService.getInstance();
691
        //login and get a sessionid
692
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
693
        String username = PropertyService.getProperty("test.mcUser");
694
        String password = PropertyService.getProperty("test.mcPassword");
695
        String response = restClient.login(username, password);
696
        String sessionid = restClient.getSessionId();
697
        SessionService sessionService = SessionService.getInstance();
698
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
699
        AuthToken token = new AuthToken(sessionid);
700
        return token;
701
	}
702
	
703
	/**
704
	 * create a doc using CrudService.create() and return its id
705
	 */
706
	private Identifier createDoc(AuthToken token, String testDoc) throws Exception
707
	{
708
	    return createDoc(token, testDoc, ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
709
	}
710
	
711
	/**
712
	 * create a doc using CrudService.create() and return its id
713
	 */
714
	private Identifier createDoc(AuthToken token, String testDoc, ObjectFormat format) throws Exception
715
	{
716
	    Identifier id;
717
        CrudService cs = CrudService.getInstance();
718
        
719
        id = new Identifier();
720
        String docid = generateDocumentId();
721
        id.setValue(docid);
722
        
723
        //create the system metadata then run the create method
724
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
725
        SystemMetadata sm = createSystemMetadata(id, testDoc, format);
726
        //create the doc
727
        cs.create(token, id, sbis, sm);
728
        return id;
729
	}
730
	
731
	/**
732
	 * create a generic SystemMetadata object for testing
733
	 */
734
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc)
735
	  throws Exception
736
	{
737
	    return createSystemMetadata(id, testDoc, 
738
	            ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
739
	}
740
	
741
	/**
742
	 * create system metadata with a specified id, doc and format
743
	 */
744
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc, ObjectFormat format)
745
	  throws Exception
746
	{
747
	    SystemMetadata sm = new SystemMetadata();
748
        //set the id
749
        sm.setIdentifier(id);
750
        sm.setObjectFormat(format);
751
        //create the checksum
752
        String checksumS = checksum(testDoc);
753
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
754
        Checksum checksum = new Checksum();
755
        checksum.setValue(checksumS);
756
        checksum.setAlgorithm(ca);
757
        sm.setChecksum(checksum);
758
        //set the size
759
        sm.setSize(testDoc.getBytes().length);
760
        //submitter
761
        Principal p = new Principal();
762
        p.setValue("joe");
763
        sm.setSubmitter(p);
764
        sm.setRightsHolder(p);
765
        sm.setDateUploaded(new Date());
766
        sm.setDateSysMetadataModified(new Date());
767
        NodeReference nr = new NodeReference();
768
        nr.setValue("metacat");
769
        sm.setOriginMemberNode(nr);
770
        sm.setAuthoritativeMemberNode(nr);
771
        return sm;
772
	}
773
	
774
	/**
775
	 *  make a document public in metacat by inserting an access document
776
	 * @param id
777
	 */
778
	private void makeDocPublic(AuthToken token, Identifier id, boolean systemMetadataToo)
779
	  throws Exception
780
	{
781
	    CrudService cs = CrudService.getInstance();
782
	    cs.setAccess(token, id, "public", "read", "allow", "allowFirst", systemMetadataToo);
783
	}
784
	
785
	/**
786
	 * print a header to start each test
787
	 */
788
	private void printTestHeader(String testName)
789
	{
790
	    System.out.println();
791
	    System.out.println("*************** " + testName + " ***************");
792
	}
793
  
794
	/**
795
	 * produce an md5 checksum for item
796
	 */
797
	private String checksum(String item)
798
	  throws Exception
799
	{
800
        StringBufferInputStream fis =  new StringBufferInputStream(item);
801
        
802
        byte[] buffer = new byte[1024];
803
        MessageDigest complete = MessageDigest.getInstance("MD5");
804
        int numRead;
805
        
806
        do 
807
        {
808
          numRead = fis.read(buffer);
809
          if (numRead > 0) 
810
          {
811
            complete.update(buffer, 0, numRead);
812
          }
813
        } while (numRead != -1);
814
        
815
        
816
        return getHex(complete.digest());
817
	}
818
	
819
	/**
820
	 * convert a byte array to a hex string
821
	 */
822
	private static String getHex( byte [] raw ) 
823
	{
824
	    final String HEXES = "0123456789ABCDEF";
825
        if ( raw == null ) {
826
          return null;
827
        }
828
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
829
        for ( final byte b : raw ) {
830
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
831
             .append(HEXES.charAt((b & 0x0F)));
832
        }
833
        return hex.toString();
834
    }
835
}
(1-1/2)