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
    private int createCount = 0;
64
    
65
    /**
66
    * consstructor for the test
67
    */
68
    public CrudServiceTest(String name)
69
    {
70
        super(name);
71
    }
72
  
73
    /**
74
	 * Establish a testing framework by initializing appropriate objects
75
	 */
76
	public void setUp() throws Exception 
77
	{
78
		super.setUp();
79
	}
80

    
81
	/**
82
	 * Release any objects after tests are complete
83
	 */
84
	public void tearDown() 
85
	{
86
	    System.out.println(createCount + " docs created in this test session.");
87
	}
88

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

    
235
	        Identifier id = new Identifier();
236
	        String docid = generateDocumentId();
237
	        id.setValue(docid);
238

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

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