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
		return suite;
104
	}
105
	
106
	/**
107
	 * test to make sure that get and listObjects methods are publicly accessible
108
	 */
109
	public void testPublicAccess()
110
	{
111
	    try
112
	    {
113
	        AuthToken token = new AuthToken("public");
114
	        //AuthToken token = getToken();
115
	        CrudService cs = CrudService.getInstance();
116
	        ObjectList ol = cs.listObjects(token, null, null, null);
117
	        System.out.println("ol: " + ol.sizeObjectInfoList());
118
	        assertTrue(ol.sizeObjectInfoList() > 0);
119
	        
120
	        ObjectInfo oi = ol.getObjectInfo(0);
121
	        String s = getDoc(token, oi.getIdentifier());
122
	        assertNotNull(s);
123
	        
124
	        try
125
	        { //try a create with the public auth.  should fail
126
	            Identifier id = new Identifier();
127
	            String docid = generateDocumentId();
128
	            id.setValue(docid);
129
	            String testDoc = getTestDoc();
130
	            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
131
	            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
132
	            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
133
	            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
134
	            //create the doc
135
	            Identifier idC = cs.create(token, id, sbis, sm);
136
	            fail("Should have thrown an auth exception");
137
	        }
138
	        catch(Exception e)
139
	        {
140
	            
141
	        }
142
	        
143
	        //create a legit doc
144
	        token = getToken();
145
	        Identifier id = new Identifier();
146
            String docid = generateDocumentId();
147
            id.setValue(docid);
148
            String testDoc = getTestDoc();
149
            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
150
            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
151
            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
152
            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
153
            //create the doc
154
            Identifier idC = cs.create(token, id, sbis, sm);
155
            //make it public, then use a public token to try to get it
156
            InputStream data = null;
157
            try
158
            {
159
                AuthToken publicToken = new AuthToken("public");
160
                data = cs.get(publicToken, id);
161
                data.read();
162
                
163
                fail("should have thrown an exception");
164
            }
165
            catch(Exception e)
166
            {
167
                /*System.out.println("%%%%%%%%%%%%%%%%%%%%%%%getting result");
168
                Object o = ((InputStreamFromOutputStream)data).getResult();
169
                System.out.println("result: " + o);
170
                System.out.println("exception thrown!");
171
                System.out.println("exception thrown: " + e.getClass().getName());*/
172
            }
173
            
174
            
175
            
176
            makeDocPublic(token, id, true);
177
            token = new AuthToken("public");
178
	        data = cs.get(token, id);
179
	    }
180
	    catch(Exception e)
181
	    {
182
	        fail("Error in testPublicAccess: " + e.getMessage());
183
	    }
184
	    
185
	}
186
	
187
	/**
188
	 * test for an error where the checksum algorithm gets appended onto the checksum.
189
	 */
190
	public void testChecksumError()
191
	{
192
	    printTestHeader("testChecksumError");
193
	    try
194
	    {
195
	        Date d1 = new Date();
196
	        CrudService cs = CrudService.getInstance();
197
	        AuthToken token = getToken();
198
	        ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
199
	        //create docs at different times
200

    
201
	        Identifier id = new Identifier();
202
	        String docid = generateDocumentId();
203
	        id.setValue(docid);
204

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

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