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.commons.io.IOUtils;
43
import org.apache.log.LogEvent;
44
import org.dataone.service.exceptions.InvalidRequest;
45
import org.dataone.service.exceptions.InvalidToken;
46
import org.dataone.service.exceptions.NotAuthorized;
47
import org.dataone.service.exceptions.NotImplemented;
48
import org.dataone.service.exceptions.ServiceFailure;
49
import org.dataone.service.types.*;
50

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

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

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

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

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

    
90
	/**
91
	 * Create a suite of tests to be run together
92
	 */
93
	public static Test suite() 
94
	{
95
		TestSuite suite = new TestSuite();
96
		suite.addTest(new CrudServiceTest("initialize"));
97
		suite.addTest(new CrudServiceTest("testSingletonAccessor"));
98
		suite.addTest(new CrudServiceTest("testCreateAndGet"));
99
		suite.addTest(new CrudServiceTest("testGetSystemMetadata"));
100
		suite.addTest(new CrudServiceTest("testUpdate"));
101
		suite.addTest(new CrudServiceTest("testListObjects"));
102
		suite.addTest(new CrudServiceTest("testAccessControl"));
103
		//suite.addTest(new CrudServiceTest("testGenerateMissingSystemMetadata"));
104
		suite.addTest(new CrudServiceTest("testGetLogRecords"));
105
		suite.addTest(new CrudServiceTest("testChecksumError"));
106
		suite.addTest(new CrudServiceTest("testPublicAccess"));
107
		suite.addTest(new CrudServiceTest("testFailedCreate"));
108
		suite.addTest(new CrudServiceTest("testChecksum"));
109
		suite.addTest(new CrudServiceTest("testDescribe"));
110
		return suite;
111
	}
112
	
113
	/**
114
	 * test the describe crud function
115
	 */
116
	public void testDescribe()
117
	{
118
	    try
119
	    {
120
	        CrudService cs = CrudService.getInstance();
121
	        AuthToken token = getToken();
122
	        
123
	        String doc = getTestDoc();
124
	        Identifier id = createDoc(token, doc);
125
	        System.out.println("ID: " + id.getValue());
126
	        makeDocPublic(token, id, true);
127
	        
128
	        SystemMetadata sm = cs.getSystemMetadata(token, id);
129
	        
130
	        DescribeResponse dr = cs.describe(token, id);
131
	        
132
	        assertTrue(dr.getDataONE_Checksum().getValue().equals(sm.getChecksum().getValue()));
133
	        assertTrue(dr.getDataONE_ObjectFormat().toString().equals(sm.getObjectFormat().toString()));
134
	        assertTrue(dr.getLast_Modified().getTime() == sm.getDateSysMetadataModified().getTime());
135
	        assertTrue(dr.getContent_Length() == sm.getSize());
136
	    }
137
	    catch(Exception e)
138
	    {
139
	        fail("Unexpected error in testDescribe: " + e.getMessage());
140
	    }
141
	}
142
	
143
	/**
144
	 * test the checksum creation
145
	 */
146
	public void testChecksum()
147
	{
148
	    try
149
	    {
150
	        CrudService cs = CrudService.getInstance();
151
	        AuthToken token = getToken();
152
	        System.out.println("token: " + token.getToken());
153
	        String doc = getTestDoc();
154
	        Identifier id = createDoc(token, doc);
155
	        System.out.println("ID: " + id.getValue());
156
            makeDocPublic(token, id, true);
157
	        String doc2 = getDoc(token, id);
158
            
159
	        String checksum = checksum(doc);
160
            Checksum checksum2 = cs.getChecksum(token, id, "MD5");
161
            System.out.println("doc: \"" + doc + "\"");
162
            System.out.println("doc2: \"" + doc2 + "\"");
163
            System.out.println("checksum1: " + checksum);
164
            System.out.println("checksum2: " + checksum2.getValue());
165
            assertTrue(checksum.equals(checksum2.getValue()));
166
            
167
	    }
168
	    catch(Exception e)
169
	    {
170
	        fail("Unexpected error in testChecksum: " + e.getMessage());
171
	    }
172
	    
173
	}
174
	
175
	/**
176
	 * insert an invalid document and make sure create fails and does not
177
	 * leave any artifacts behind
178
	 */
179
	public void testFailedCreate()
180
	{
181
	    try
182
	    {
183
	        String invalidDoc = "<xxx></yyy>";
184
	        System.out.println("trying to insert doc " + invalidDoc);
185
	        CrudService cs = CrudService.getInstance();
186
            AuthToken token = getToken();
187
            //run create
188
            try
189
            {
190
                Identifier id = createDoc(token, invalidDoc);
191
                fail("Should have thrown an exception.");
192
            }
193
            catch(Exception e)
194
            {
195
                //e.printStackTrace();
196
            }
197
            
198
	    }
199
	    catch(Exception e)
200
	    {
201
	        fail("unexpected exception in testFailedCreate: " + e.getMessage());
202
	    }
203
	}
204
	
205
	/**
206
	 * test to make sure that get and listObjects methods are publicly accessible
207
	 */
208
	public void testPublicAccess()
209
	{
210
	    try
211
	    {
212
	        AuthToken token = new AuthToken("public");
213
	        //AuthToken token = getToken();
214
	        CrudService cs = CrudService.getInstance();
215
	        ObjectList ol = cs.listObjects(token, null, null, null);
216
	        System.out.println("ol: " + ol.sizeObjectInfoList());
217
	        assertTrue(ol.sizeObjectInfoList() > 0);
218
	        
219
	        ObjectInfo oi = ol.getObjectInfo(0);
220
	        String s = getDoc(token, oi.getIdentifier());
221
	        assertNotNull(s);
222
	        
223
	        try
224
	        { //try a create with the public auth.  should fail
225
	            Identifier id = new Identifier();
226
	            String docid = generateDocumentId();
227
	            id.setValue(docid);
228
	            String testDoc = getTestDoc();
229
	            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
230
	            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
231
	            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
232
	            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
233
	            //create the doc
234
	            Identifier idC = cs.create(token, id, sbis, sm);
235
	            fail("Should have thrown an auth exception");
236
	        }
237
	        catch(Exception e)
238
	        {
239
	            
240
	        }
241
	        
242
	        //create a legit doc
243
	        token = getToken();
244
	        Identifier id = new Identifier();
245
            String docid = generateDocumentId();
246
            id.setValue(docid);
247
            String testDoc = getTestDoc();
248
            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
249
            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
250
            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
251
            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
252
            //create the doc
253
            Identifier idC = cs.create(token, id, sbis, sm);
254
            //make it public, then use a public token to try to get it
255
            InputStream data = null;
256
            try
257
            {
258
                AuthToken publicToken = new AuthToken("public");
259
                data = cs.get(publicToken, id);
260
                data.read();
261
                
262
                fail("should have thrown an exception");
263
            }
264
            catch(Exception e)
265
            {
266
                /*System.out.println("%%%%%%%%%%%%%%%%%%%%%%%getting result");
267
                Object o = ((InputStreamFromOutputStream)data).getResult();
268
                System.out.println("result: " + o);
269
                System.out.println("exception thrown!");
270
                System.out.println("exception thrown: " + e.getClass().getName());*/
271
            }
272
            
273
            
274
            
275
            makeDocPublic(token, id, true);
276
            token = new AuthToken("public");
277
	        data = cs.get(token, id);
278
	    }
279
	    catch(Exception e)
280
	    {
281
	        fail("Error in testPublicAccess: " + e.getMessage());
282
	    }
283
	    
284
	}
285
	
286
	/**
287
	 * test for an error where the checksum algorithm gets appended onto the checksum.
288
	 */
289
	public void testChecksumError()
290
	{
291
	    printTestHeader("testChecksumError");
292
	    try
293
	    {
294
	        Date d1 = new Date(new Date().getTime() - 5000);
295
	        CrudService cs = CrudService.getInstance();
296
	        AuthToken token = getToken();
297
	        ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
298
	        //create docs at different times
299

    
300
	        Identifier id = new Identifier();
301
	        String docid = "test." + new Date().getTime();
302
	        id.setValue(docid);
303

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

    
696
	/**
697
	 * getInstance()
698
	 */
699
	public void testSingletonAccessor()
700
	{
701
	    printTestHeader("testSingletonAccessor");
702
	    CrudService cs = CrudService.getInstance();
703
	    assertNotNull(cs);
704
	}
705
	
706
	/**
707
	 * Run an initial test that always passes to check that the test harness is
708
	 * working.
709
	 */
710
	public void initialize() 
711
	{
712
	    printTestHeader("initialize");
713
		assertTrue(1 == 1);
714
	}
715
	
716
	/**
717
	 * return the systemMetadata object for id
718
	 */
719
	private SystemMetadata getSystemMetadata(AuthToken token, Identifier id)
720
	  throws Exception
721
	{
722
	    CrudService cs = CrudService.getInstance();
723
	    return cs.getSystemMetadata(token, id);
724
	}
725
	
726
	/**
727
	 * get a doc from metacat using CrudService.get()
728
	 */
729
	private String getDoc(AuthToken token, Identifier id)
730
	  throws Exception
731
	{
732
	    CrudService cs = CrudService.getInstance();
733
        InputStream gotDocStream = cs.get(token, id);
734
        return IOUtils.toString(gotDocStream);
735
	}
736
	
737
	/**
738
	 * return a test document
739
	 */
740
	private String getTestDoc()
741
	{
742
	    return "<?xml version=\"1.0\"?><test><somecontent>This is some content XXX</somecontent></test>\n";
743
	}
744
	
745
	/**
746
	 * authenticate and return a token
747
	 */
748
	private AuthToken getToken()
749
	  throws Exception
750
	{
751
	    CrudService cs = CrudService.getInstance();
752
        //login and get a sessionid
753
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
754
        String username = PropertyService.getProperty("test.mcUser");
755
        String password = PropertyService.getProperty("test.mcPassword");
756
        String response = restClient.login(username, password);
757
        String sessionid = restClient.getSessionId();
758
        SessionService sessionService = SessionService.getInstance();
759
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
760
        AuthToken token = new AuthToken(sessionid);
761
        return token;
762
	}
763
	
764
	/**
765
	 * create a doc using CrudService.create() and return its id
766
	 */
767
	private Identifier createDoc(AuthToken token, String testDoc) throws Exception
768
	{
769
	    return createDoc(token, testDoc, ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
770
	}
771
	
772
	/**
773
	 * create a doc using CrudService.create() and return its id
774
	 */
775
	private Identifier createDoc(AuthToken token, String testDoc, ObjectFormat format) throws Exception
776
	{
777
	    Identifier id;
778
        CrudService cs = CrudService.getInstance();
779
        
780
        id = new Identifier();
781
        String docid = generateDocumentId();
782
        id.setValue(docid);
783
        
784
        //create the system metadata then run the create method
785
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
786
        SystemMetadata sm = createSystemMetadata(id, testDoc, format);
787
        //create the doc
788
        cs.create(token, id, sbis, sm);
789
        createCount++;
790
        return id;
791
	}
792
	
793
	/**
794
	 * create a generic SystemMetadata object for testing
795
	 */
796
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc)
797
	  throws Exception
798
	{
799
	    return createSystemMetadata(id, testDoc, 
800
	            ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
801
	}
802
	
803
	/**
804
	 * create system metadata with a specified id, doc and format
805
	 */
806
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc, ObjectFormat format)
807
	  throws Exception
808
	{
809
	    SystemMetadata sm = new SystemMetadata();
810
        //set the id
811
        sm.setIdentifier(id);
812
        sm.setObjectFormat(format);
813
        //create the checksum
814
        String checksumS = checksum(testDoc);
815
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
816
        Checksum checksum = new Checksum();
817
        checksum.setValue(checksumS);
818
        checksum.setAlgorithm(ca);
819
        sm.setChecksum(checksum);
820
        //set the size
821
        sm.setSize(testDoc.getBytes().length);
822
        //submitter
823
        Principal p = new Principal();
824
        p.setValue("joe");
825
        sm.setSubmitter(p);
826
        sm.setRightsHolder(p);
827
        sm.setDateUploaded(new Date());
828
        sm.setDateSysMetadataModified(new Date());
829
        NodeReference nr = new NodeReference();
830
        nr.setValue("metacat");
831
        sm.setOriginMemberNode(nr);
832
        sm.setAuthoritativeMemberNode(nr);
833
        return sm;
834
	}
835
	
836
	/**
837
	 *  make a document public in metacat by inserting an access document
838
	 * @param id
839
	 */
840
	private void makeDocPublic(AuthToken token, Identifier id, boolean systemMetadataToo)
841
	  throws Exception
842
	{
843
	    CrudService cs = CrudService.getInstance();
844
	    cs.setAccess(token, id, "public", "read", "allow", "allowFirst", systemMetadataToo);
845
	}
846
	
847
	/**
848
	 * print a header to start each test
849
	 */
850
	private void printTestHeader(String testName)
851
	{
852
	    System.out.println();
853
	    System.out.println("*************** " + testName + " ***************");
854
	}
855
  
856
	/**
857
	 * produce an md5 checksum for item
858
	 */
859
	private String checksum(String item)
860
	  throws Exception
861
	{
862
        StringBufferInputStream fis =  new StringBufferInputStream(item);
863
        
864
        byte[] buffer = new byte[1024];
865
        MessageDigest complete = MessageDigest.getInstance("MD5");
866
        int numRead;
867
        
868
        do 
869
        {
870
          numRead = fis.read(buffer);
871
          if (numRead > 0) 
872
          {
873
            complete.update(buffer, 0, numRead);
874
          }
875
        } while (numRead != -1);
876
        
877
        
878
        return getHex(complete.digest());
879
	}
880
	
881
	/**
882
	 * convert a byte array to a hex string
883
	 */
884
	private static String getHex( byte [] raw ) 
885
	{
886
	    final String HEXES = "0123456789ABCDEF";
887
        if ( raw == null ) {
888
          return null;
889
        }
890
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
891
        for ( final byte b : raw ) {
892
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
893
             .append(HEXES.charAt((b & 0x0F)));
894
        }
895
        return hex.toString();
896
    }
897
}
(1-1/3)