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.MetaCatServlet;
36
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
37
import edu.ucsb.nceas.metacat.client.MetacatException;
38
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
39
import edu.ucsb.nceas.metacat.dataone.CrudService;
40
import junit.framework.Test;
41
import junit.framework.TestSuite;
42

    
43
import org.apache.commons.io.IOUtils;
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("testGetLogRecords"));
104
		suite.addTest(new CrudServiceTest("testChecksumError"));
105
		suite.addTest(new CrudServiceTest("testPublicAccess"));
106
		suite.addTest(new CrudServiceTest("testFailedCreate"));
107
		suite.addTest(new CrudServiceTest("testChecksum"));
108
		suite.addTest(new CrudServiceTest("testDescribe"));
109
		suite.addTest(new CrudServiceTest("testDelete"));
110
		suite.addTest(new CrudServiceTest("testSemiColonsInIdentifiers"));
111
		//suite.addTest(new CrudServiceTest("testGenerateMissingSystemMetadata"));
112
		return suite;
113
	}
114
	
115
	/**
116
	 * test for the use of semi colons in identifiers
117
	 * in response to https://redmine.dataone.org/issues/1143
118
	 */
119
	public void testSemiColonsInIdentifiers()
120
	{
121
	    try
122
        {
123
            CrudService cs = CrudService.getInstance();
124
            AuthToken token = getToken();
125
            String testDoc = getTestDoc();
126
            
127
            Identifier id = new Identifier();
128
            id.setValue("someid;id;with;semi;colons;in;it." + new Date().getTime());
129
            String docid = generateDocumentId();
130
            
131
            //create the system metadata then run the create method
132
            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
133
            SystemMetadata sm = createSystemMetadata(id, testDoc, 
134
                    ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
135
            //create the doc
136
            Identifier rGuid = cs.create(token, id, sbis, sm);
137
            
138
            System.out.println("ID: " + rGuid.getValue());
139
            assertTrue(rGuid.toString().equals(id.toString())); 
140
            System.out.println("created doc with id " + id.getValue());
141
        }
142
        catch(Exception e)
143
        {
144
            fail("Unexpected error in testDescribe: " + e.getMessage());
145
        }
146
	}
147
	
148
	/**
149
	 * test the delete function
150
	 */
151
	public void testDelete()
152
	{
153
	    try
154
        {
155
            CrudService cs = CrudService.getInstance();
156
            AuthToken token = getToken();
157
            String doc = getTestDoc();
158
            Identifier id = createDoc(token, doc);
159
            System.out.println("ID: " + id.getValue());
160
            makeDocPublic(token, id, true);
161
            cs.get(token, id);
162
            cs.delete(token, id);
163
            //there should be a try/catch around the next statement
164
            //to make sure that the document is no longer readable,
165
            //but because the data is output in a 2nd thread, the
166
            //exception does not get caught here.  See 
167
            //https://redmine.dataone.org/issues/1079
168
            //cs.get(token, id);
169
        }
170
        catch(Exception e)
171
        {
172
            fail("Unexpected error in testDescribe: " + e.getMessage());
173
        }
174
	}
175
	
176
	/**
177
	 * test the describe crud function
178
	 */
179
	public void testDescribe()
180
	{
181
	    try
182
	    {
183
	        CrudService cs = CrudService.getInstance();
184
	        AuthToken token = getToken();
185
	        
186
	        String doc = getTestDoc();
187
	        Identifier id = createDoc(token, doc);
188
	        System.out.println("ID: " + id.getValue());
189
	        makeDocPublic(token, id, true);
190
	        
191
	        SystemMetadata sm = cs.getSystemMetadata(token, id);
192
	        
193
	        DescribeResponse dr = cs.describe(token, id);
194
	        
195
	        assertTrue(dr.getDataONE_Checksum().getValue().equals(sm.getChecksum().getValue()));
196
	        assertTrue(dr.getDataONE_ObjectFormat().toString().equals(sm.getObjectFormat().toString()));
197
	        assertTrue(dr.getLast_Modified().getTime() == sm.getDateSysMetadataModified().getTime());
198
	        assertTrue(dr.getContent_Length() == sm.getSize());
199
	    }
200
	    catch(Exception e)
201
	    {
202
	        fail("Unexpected error in testDescribe: " + e.getMessage());
203
	    }
204
	}
205
	
206
	/**
207
	 * test the checksum creation
208
	 */
209
	public void testChecksum()
210
	{
211
	    try
212
	    {
213
	        CrudService cs = CrudService.getInstance();
214
	        AuthToken token = getToken();
215
	        System.out.println("token: " + token.getToken());
216
	        String doc = getTestDoc();
217
	        Identifier id = createDoc(token, doc);
218
	        System.out.println("ID: " + id.getValue());
219
            makeDocPublic(token, id, true);
220
	        String doc2 = getDoc(token, id);
221
            
222
	        String checksum = checksum(doc);
223
            Checksum checksum2 = cs.getChecksum(token, id, "MD5");
224
            System.out.println("doc: \"" + doc + "\"");
225
            System.out.println("doc2: \"" + doc2 + "\"");
226
            System.out.println("checksum1: " + checksum);
227
            System.out.println("checksum2: " + checksum2.getValue());
228
            assertTrue(checksum.equals(checksum2.getValue()));
229
            
230
	    }
231
	    catch(Exception e)
232
	    {
233
	        fail("Unexpected error in testChecksum: " + e.getMessage());
234
	    }
235
	    
236
	}
237
	
238
	/**
239
	 * insert an invalid document and make sure create fails and does not
240
	 * leave any artifacts behind
241
	 */
242
	public void testFailedCreate()
243
	{
244
	    try
245
	    {
246
	        String invalidDoc = "<xxx></yyy>";
247
	        System.out.println("trying to insert doc " + invalidDoc);
248
	        CrudService cs = CrudService.getInstance();
249
            AuthToken token = getToken();
250
            //run create
251
            try
252
            {
253
                Identifier id = createDoc(token, invalidDoc);
254
                fail("Should have thrown an exception.");
255
            }
256
            catch(Exception e)
257
            {
258
                //e.printStackTrace();
259
            }
260
            
261
	    }
262
	    catch(Exception e)
263
	    {
264
	        fail("unexpected exception in testFailedCreate: " + e.getMessage());
265
	    }
266
	}
267
	
268
	/**
269
	 * test to make sure that get and listObjects methods are publicly accessible
270
	 */
271
	public void testPublicAccess()
272
	{
273
	    try
274
	    {
275
	        System.out.println("********************* testPublicAccess *********************");
276
	        AuthToken token = new AuthToken("public");
277
	        //AuthToken token = getToken();
278
	        CrudService cs = CrudService.getInstance();
279
	        ObjectList ol = cs.listObjects(token, null, null, null);
280
	        System.out.println("ol: " + ol.sizeObjectInfoList());
281
	        assertTrue(ol.sizeObjectInfoList() > 0);
282
	        
283
	        ObjectInfo oi = ol.getObjectInfo(0);
284
	        String s = getDoc(token, oi.getIdentifier());
285
	        assertNotNull(s);
286
	        
287
	        try
288
	        { //try a create with the public auth.  should fail
289
	            Identifier id = new Identifier();
290
	            String docid = generateDocumentId();
291
	            id.setValue(docid);
292
	            String testDoc = getTestDoc();
293
	            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
294
	            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
295
	            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
296
	            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
297
	            //create the doc
298
	            Identifier idC = cs.create(token, id, sbis, sm);
299
	            fail("Should have thrown an auth exception");
300
	        }
301
	        catch(Exception e)
302
	        {
303
	            
304
	        }
305
	        
306
	        //create a legit doc
307
	        token = getToken();
308
	        Identifier id = new Identifier();
309
            String docid = generateDocumentId();
310
            id.setValue(docid);
311
            String testDoc = getTestDoc();
312
            StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
313
            ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
314
            SystemMetadata sm = createSystemMetadata(id, testDoc, of1);
315
            assertFalse(sm.getChecksum().getValue().startsWith("MD5"));
316
            //create the doc
317
            Identifier idC = cs.create(token, id, sbis, sm);
318
            //make it public, then use a public token to try to get it
319
            InputStream data = null;
320
            try
321
            {
322
                AuthToken publicToken = new AuthToken("public");
323
                data = cs.get(publicToken, id);
324
                data.read();
325
                
326
                fail("should have thrown an exception");
327
            }
328
            catch(Exception e)
329
            {
330
                /*System.out.println("%%%%%%%%%%%%%%%%%%%%%%%getting result");
331
                Object o = ((InputStreamFromOutputStream)data).getResult();
332
                System.out.println("result: " + o);
333
                System.out.println("exception thrown!");
334
                System.out.println("exception thrown: " + e.getClass().getName());*/
335
            }
336
            
337
            
338
            
339
            makeDocPublic(token, id, true);
340
            token = new AuthToken("public");
341
	        data = cs.get(token, id);
342
	    }
343
	    catch(Exception e)
344
	    {
345
	        fail("Error in testPublicAccess: " + e.getMessage());
346
	    }
347
	    
348
	}
349
	
350
	/**
351
	 * test for an error where the checksum algorithm gets appended onto the checksum.
352
	 */
353
	public void testChecksumError()
354
	{
355
	    printTestHeader("testChecksumError");
356
	    try
357
	    {
358
	        Date d1 = new Date(new Date().getTime() - 5000);
359
	        CrudService cs = CrudService.getInstance();
360
	        AuthToken token = getToken();
361
	        ObjectFormat of1 = ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0");
362
	        //create docs at different times
363

    
364
	        Identifier id = new Identifier();
365
	        String docid = "test." + new Date().getTime();
366
	        id.setValue(docid);
367

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

    
761
	/**
762
	 * getInstance()
763
	 */
764
	public void testSingletonAccessor()
765
	{
766
	    printTestHeader("testSingletonAccessor");
767
	    CrudService cs = CrudService.getInstance();
768
	    assertNotNull(cs);
769
	}
770
	
771
	/**
772
	 * Run an initial test that always passes to check that the test harness is
773
	 * working.
774
	 */
775
	public void initialize() 
776
	{
777
	    printTestHeader("initialize");
778
		assertTrue(1 == 1);
779
	}
780
	
781
	/**
782
	 * return the systemMetadata object for id
783
	 */
784
	private SystemMetadata getSystemMetadata(AuthToken token, Identifier id)
785
	  throws Exception
786
	{
787
	    CrudService cs = CrudService.getInstance();
788
	    return cs.getSystemMetadata(token, id);
789
	}
790
	
791
	/**
792
	 * get a doc from metacat using CrudService.get()
793
	 */
794
	private String getDoc(AuthToken token, Identifier id)
795
	  throws Exception
796
	{
797
	    CrudService cs = CrudService.getInstance();
798
        InputStream gotDocStream = cs.get(token, id);
799
        return IOUtils.toString(gotDocStream);
800
	}
801
	
802
	private String getTestDoc()
803
	{
804
	    return getTestDoc(null);
805
	}
806
	
807
	/**
808
	 * return a test document.  objectFormat should come from MCTestCase
809
	 */
810
	private String getTestDoc(String objectFormat)
811
	{
812
	    if(objectFormat == null)
813
	    {
814
	        return "<?xml version=\"1.0\"?><test><somecontent>This is some content XXX</somecontent></test>\n";
815
	    }
816
	    
817
	    String accessBlock = getAccessBlock("public", true, true,
818
                false, false, false);
819
	    
820
	    
821
	    return getTestEmlDoc("Test identifier manager", objectFormat, null,
822
	                null, "http://fake.example.com/somedata", null,
823
	                accessBlock, null, null,
824
	                null, null);
825
	}
826
	
827
	/**
828
	 * authenticate and return a token
829
	 * use the test.mcUser and test.mcPassword username/password combo
830
	 */
831
	private AuthToken getToken()
832
	  throws Exception
833
	{
834
        String username = PropertyService.getProperty("test.mcUser");
835
        String password = PropertyService.getProperty("test.mcPassword");
836
        return getToken(username, password);
837
	}
838
	
839
	/**
840
	 * authenticate and return a token using the given credentials
841
	 */
842
	private AuthToken getToken(String username, String password)
843
	  throws Exception
844
	{
845
	    CrudService cs = CrudService.getInstance();
846
        //login and get a sessionid
847
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
848
        String response = restClient.login(username, password);
849
        String sessionid = restClient.getSessionId();
850
        SessionService sessionService = SessionService.getInstance();
851
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
852
        AuthToken token = new AuthToken(sessionid);
853
        return token;
854
	}
855
	
856
	/**
857
	 * create a doc using CrudService.create() and return its id
858
	 */
859
	private Identifier createDoc(AuthToken token, String testDoc) throws Exception
860
	{
861
	    return createDoc(token, testDoc, ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
862
	}
863
	
864
	/**
865
	 * create a doc using CrudService.create() and return its id
866
	 */
867
	private Identifier createDoc(AuthToken token, String testDoc, ObjectFormat format) throws Exception
868
	{
869
	    Identifier id;
870
        CrudService cs = CrudService.getInstance();
871
        
872
        id = new Identifier();
873
        String docid = generateDocumentId();
874
        id.setValue(docid);
875
        
876
        //create the system metadata then run the create method
877
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
878
        SystemMetadata sm = createSystemMetadata(id, testDoc, format);
879
        //create the doc
880
        cs.create(token, id, sbis, sm);
881
        createCount++;
882
        return id;
883
	}
884
	
885
	/**
886
	 * create a generic SystemMetadata object for testing
887
	 */
888
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc)
889
	  throws Exception
890
	{
891
	    return createSystemMetadata(id, testDoc, 
892
	            ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
893
	}
894
	
895
	/**
896
	 * create system metadata with a specified id, doc and format
897
	 */
898
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc, ObjectFormat format)
899
	  throws Exception
900
	{
901
	    SystemMetadata sm = new SystemMetadata();
902
        //set the id
903
        sm.setIdentifier(id);
904
        sm.setObjectFormat(format);
905
        //create the checksum
906
        String checksumS = checksum(testDoc);
907
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
908
        Checksum checksum = new Checksum();
909
        checksum.setValue(checksumS);
910
        checksum.setAlgorithm(ca);
911
        sm.setChecksum(checksum);
912
        //set the size
913
        sm.setSize(testDoc.getBytes(MetaCatServlet.DEFAULT_ENCODING).length);
914
        //submitter
915
        Principal p = new Principal();
916
        p.setValue("joe");
917
        sm.setSubmitter(p);
918
        sm.setRightsHolder(p);
919
        sm.setDateUploaded(new Date());
920
        sm.setDateSysMetadataModified(new Date());
921
        NodeReference nr = new NodeReference();
922
        nr.setValue("metacat");
923
        sm.setOriginMemberNode(nr);
924
        sm.setAuthoritativeMemberNode(nr);
925
        return sm;
926
	}
927
	
928
	/**
929
	 *  make a document public in metacat by inserting an access document
930
	 * @param id
931
	 */
932
	private void makeDocPublic(AuthToken token, Identifier id, boolean systemMetadataToo)
933
	  throws Exception
934
	{
935
	    CrudService cs = CrudService.getInstance();
936
	    cs.setAccess(token, id, "public", "read", "allow", "allowFirst", systemMetadataToo);
937
	}
938
	
939
	/**
940
	 * print a header to start each test
941
	 */
942
	private void printTestHeader(String testName)
943
	{
944
	    System.out.println();
945
	    System.out.println("*************** " + testName + " ***************");
946
	}
947
  
948
	/**
949
	 * produce an md5 checksum for item
950
	 */
951
	private String checksum(String item)
952
	  throws Exception
953
	{
954
        StringBufferInputStream fis =  new StringBufferInputStream(item);
955
        
956
        byte[] buffer = new byte[1024];
957
        MessageDigest complete = MessageDigest.getInstance("MD5");
958
        int numRead;
959
        
960
        do 
961
        {
962
          numRead = fis.read(buffer);
963
          if (numRead > 0) 
964
          {
965
            complete.update(buffer, 0, numRead);
966
          }
967
        } while (numRead != -1);
968
        
969
        
970
        return getHex(complete.digest());
971
	}
972
	
973
	/**
974
	 * convert a byte array to a hex string
975
	 */
976
	private static String getHex( byte [] raw ) 
977
	{
978
	    final String HEXES = "0123456789ABCDEF";
979
        if ( raw == null ) {
980
          return null;
981
        }
982
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
983
        for ( final byte b : raw ) {
984
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
985
             .append(HEXES.charAt((b & 0x0F)));
986
        }
987
        return hex.toString();
988
    }
989
}
(1-1/3)