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

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

    
84
	/**
85
	 * Create a suite of tests to be run together
86
	 */
87
	public static Test suite() 
88
	{
89
		TestSuite suite = new TestSuite();
90
		/*suite.addTest(new CrudServiceTest("initialize"));
91
		suite.addTest(new CrudServiceTest("testSingletonAccessor"));
92
		suite.addTest(new CrudServiceTest("testCreateAndGet"));
93
		suite.addTest(new CrudServiceTest("testGetSystemMetadata"));
94
		suite.addTest(new CrudServiceTest("testUpdate"));
95
		suite.addTest(new CrudServiceTest("testListObjects"));
96
		suite.addTest(new CrudServiceTest("testAccessControl"));
97
		suite.addTest(new CrudServiceTest("testGenerateMissingSystemMetadata"));*/
98
		suite.addTest(new CrudServiceTest("testGetLogRecords"));
99
		//suite.addTest(new CrudServiceTest("testChecksumError"));
100
		//suite.addTest(new CrudServiceTest("testPublicAccess"));
101
		return suite;
102
	}
103
	
104
	/**
105
	 * test to make sure that get and listObjects methods are publicly accessible
106
	 */
107
	public void testPublicAccess()
108
	{
109
	    try
110
	    {
111
	        AuthToken token = new AuthToken("public");
112
	        //AuthToken token = getToken();
113
	        CrudService cs = CrudService.getInstance();
114
	        ObjectList ol = cs.listObjects(token, null, null, null);
115
	        System.out.println("ol: " + ol.sizeObjectInfoList());
116
	        assertTrue(ol.sizeObjectInfoList() > 0);
117
	        
118
	        ObjectInfo oi = ol.getObjectInfo(0);
119
	        String s = getDoc(token, oi.getIdentifier());
120
	        assertNotNull(s);
121
	        
122
	        try
123
	        { //try a create with the public auth.  should fail
124
	            Identifier id = new Identifier();
125
	            String docid = generateDocumentId();
126
	            id.setValue(docid);
127
	            String testDoc = getTestDoc();
128
	            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
129
	            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
130
	            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
131
	            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
132
	            //create the doc
133
	            Identifier idC = cs.create(token, id, sbis, sm);
134
	            fail("Should have thrown an auth exception");
135
	        }
136
	        catch(Exception e)
137
	        {
138
	            
139
	        }
140
	    }
141
	    catch(Exception e)
142
	    {
143
	        fail("Error in testPublicAccess: " + e.getMessage());
144
	    }
145
	    
146
	}
147
	
148
	/**
149
	 * test for an error where the checksum algorithm gets appended onto the checksum.
150
	 */
151
	public void testChecksumError()
152
	{
153
	    printTestHeader("testChecksumError");
154
	    try
155
	    {
156
	        Date d1 = new Date();
157
	        CrudService cs = CrudService.getInstance();
158
	        AuthToken token = getToken();
159
	        ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
160
	        //create docs at different times
161

    
162
	        Identifier id = new Identifier();
163
	        String docid = generateDocumentId();
164
	        id.setValue(docid);
165

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

    
556
	/**
557
	 * getInstance()
558
	 */
559
	public void testSingletonAccessor()
560
	{
561
	    printTestHeader("testSingletonAccessor");
562
	    CrudService cs = CrudService.getInstance();
563
	    assertNotNull(cs);
564
	}
565
	
566
	/**
567
	 * Run an initial test that always passes to check that the test harness is
568
	 * working.
569
	 */
570
	public void initialize() 
571
	{
572
	    printTestHeader("initialize");
573
		assertTrue(1 == 1);
574
	}
575
	
576
	/**
577
	 * return the systemMetadata object for id
578
	 */
579
	private SystemMetadata getSystemMetadata(AuthToken token, Identifier id)
580
	  throws Exception
581
	{
582
	    CrudService cs = CrudService.getInstance();
583
	    return cs.getSystemMetadata(token, id);
584
	}
585
	
586
	/**
587
	 * get a doc from metacat using CrudService.get()
588
	 */
589
	private String getDoc(AuthToken token, Identifier id)
590
	  throws Exception
591
	{
592
	    CrudService cs = CrudService.getInstance();
593
	    //try to get the same doc then compare them
594
        InputStream gotDocStream = cs.get(token, id);
595
        StringBuffer sb = new StringBuffer();
596
        byte[] b = new byte[1024];
597
        int numread = gotDocStream.read(b, 0, 1024);
598
        while(numread != -1)
599
        {
600
            sb.append(new String(b, 0, numread));
601
            numread = gotDocStream.read(b, 0, 1024);
602
        }
603
        return sb.toString();
604
	}
605
	
606
	/**
607
	 * return a test document
608
	 */
609
	private String getTestDoc()
610
	{
611
	    return "<?xml version=\"1.0\"?><test><somecontent>This is some content XXX</somecontent></test>\n";
612
	}
613
	
614
	/**
615
	 * authenticate and return a token
616
	 */
617
	private AuthToken getToken()
618
	  throws Exception
619
	{
620
	    CrudService cs = CrudService.getInstance();
621
        //login and get a sessionid
622
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
623
        String username = PropertyService.getProperty("test.mcUser");
624
        String password = PropertyService.getProperty("test.mcPassword");
625
        String response = restClient.login(username, password);
626
        String sessionid = restClient.getSessionId();
627
        SessionService sessionService = SessionService.getInstance();
628
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
629
        AuthToken token = new AuthToken(sessionid);
630
        return token;
631
	}
632
	
633
	/**
634
	 * create a doc using CrudService.create() and return its id
635
	 */
636
	private Identifier createDoc(AuthToken token, String testDoc) throws Exception
637
	{
638
	    return createDoc(token, testDoc, ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
639
	}
640
	
641
	/**
642
	 * create a doc using CrudService.create() and return its id
643
	 */
644
	private Identifier createDoc(AuthToken token, String testDoc, ObjectFormat format) throws Exception
645
	{
646
	    Identifier id;
647
        CrudService cs = CrudService.getInstance();
648
        
649
        id = new Identifier();
650
        String docid = generateDocumentId();
651
        id.setValue(docid);
652
        
653
        //create the system metadata then run the create method
654
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
655
        SystemMetadata sm = createSystemMetadata(id, testDoc, format);
656
        //create the doc
657
        cs.create(token, id, sbis, sm);
658
        return id;
659
	}
660
	
661
	/**
662
	 * create a generic SystemMetadata object for testing
663
	 */
664
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc)
665
	  throws Exception
666
	{
667
	    return createSystemMetadata(id, testDoc, 
668
	            ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
669
	}
670
	
671
	/**
672
	 * create system metadata with a specified id, doc and format
673
	 */
674
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc, ObjectFormat format)
675
	  throws Exception
676
	{
677
	    SystemMetadata sm = new SystemMetadata();
678
        //set the id
679
        sm.setIdentifier(id);
680
        sm.setObjectFormat(format);
681
        //create the checksum
682
        String checksumS = checksum(testDoc);
683
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
684
        Checksum checksum = new Checksum();
685
        checksum.setValue(checksumS);
686
        checksum.setAlgorithm(ca);
687
        sm.setChecksum(checksum);
688
        //set the size
689
        sm.setSize(testDoc.getBytes().length);
690
        //submitter
691
        Principal p = new Principal();
692
        p.setValue("joe");
693
        sm.setSubmitter(p);
694
        sm.setRightsHolder(p);
695
        sm.setDateUploaded(new Date());
696
        sm.setDateSysMetadataModified(new Date());
697
        NodeReference nr = new NodeReference();
698
        nr.setValue("metacat");
699
        sm.setOriginMemberNode(nr);
700
        sm.setAuthoritativeMemberNode(nr);
701
        return sm;
702
	}
703
	
704
	/**
705
	 *  make a document public in metacat by inserting an access document
706
	 * @param id
707
	 */
708
	private void makeDocPublic(AuthToken token, Identifier id, boolean systemMetadataToo)
709
	  throws Exception
710
	{
711
	    CrudService cs = CrudService.getInstance();
712
	    IdentifierManager im = IdentifierManager.getInstance();
713
	    cs.setAccess(token, id, "public", "read", "allow", "allowFirst");
714
	    if(systemMetadataToo)
715
	    {
716
	        String smidS = im.getSystemMetadataId(id.getValue());
717
	        Identifier smid = new Identifier();
718
	        smid.setValue(smidS);
719
	        cs.setAccess(token, smid, "public", "read", "allow", "allowFirst");
720
	    }
721
	}
722
	
723
	/**
724
	 * print a header to start each test
725
	 */
726
	private void printTestHeader(String testName)
727
	{
728
	    System.out.println();
729
	    System.out.println("*************** " + testName + " ***************");
730
	}
731
  
732
	/**
733
	 * produce an md5 checksum for item
734
	 */
735
	private String checksum(String item)
736
	  throws Exception
737
	{
738
        StringBufferInputStream fis =  new StringBufferInputStream(item);
739
        
740
        byte[] buffer = new byte[1024];
741
        MessageDigest complete = MessageDigest.getInstance("MD5");
742
        int numRead;
743
        
744
        do 
745
        {
746
          numRead = fis.read(buffer);
747
          if (numRead > 0) 
748
          {
749
            complete.update(buffer, 0, numRead);
750
          }
751
        } while (numRead != -1);
752
        
753
        
754
        return getHex(complete.digest());
755
	}
756
	
757
	/**
758
	 * convert a byte array to a hex string
759
	 */
760
	private static String getHex( byte [] raw ) 
761
	{
762
	    final String HEXES = "0123456789ABCDEF";
763
        if ( raw == null ) {
764
          return null;
765
        }
766
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
767
        for ( final byte b : raw ) {
768
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
769
             .append(HEXES.charAt((b & 0x0F)));
770
        }
771
        return hex.toString();
772
    }
773
}
(1-1/2)