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

    
41
import org.dataone.service.types.*;
42

    
43
import edu.ucsb.nceas.metacat.properties.PropertyService;
44
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
45

    
46
import edu.ucsb.nceas.metacat.service.SessionService;
47
import edu.ucsb.nceas.metacat.util.SessionData;
48

    
49
/**
50
 * A JUnit test for testing the dataone CrudService class
51
 */
52
public class CrudServiceTest extends MCTestCase 
53
{   
54
    /**
55
    * consstructor for the test
56
    */
57
    public CrudServiceTest(String name)
58
    {
59
        super(name);
60
    }
61
  
62
    /**
63
	 * Establish a testing framework by initializing appropriate objects
64
	 */
65
	public void setUp() throws Exception 
66
	{
67
		super.setUp();
68
	}
69

    
70
	/**
71
	 * Release any objects after tests are complete
72
	 */
73
	public void tearDown() 
74
	{
75
	}
76

    
77
	/**
78
	 * Create a suite of tests to be run together
79
	 */
80
	public static Test suite() 
81
	{
82
		TestSuite suite = new TestSuite();
83
		/*suite.addTest(new CrudServiceTest("initialize"));
84
		suite.addTest(new CrudServiceTest("testSingletonAccessor"));
85
		suite.addTest(new CrudServiceTest("testCreateAndGet"));
86
		suite.addTest(new CrudServiceTest("testGetSystemMetadata"));*/
87
		suite.addTest(new CrudServiceTest("testUpdate"));
88
		//suite.addTest(new CrudServiceTest(""));
89
		//suite.addTest(new CrudServiceTest(""));
90
		return suite;
91
	}
92
	
93
	/**
94
	 * public Identifier update(AuthToken token, Identifier guid, 
95
     *       InputStream object, Identifier obsoletedGuid, SystemMetadata sysmeta) 
96
     *         throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, 
97
     *           UnsupportedType, InsufficientResources, NotFound, InvalidSystemMetadata, 
98
     *           NotImplemented
99
	 */
100
	public void testUpdate()
101
	{
102
	    printTestHeader("testUpdate");
103
	    try
104
	    {
105
	        CrudService cs = CrudService.getInstance();
106
	        AuthToken token = getToken();
107
            //create a doc
108
            System.out.println("CST: creating document");
109
            Identifier id = createDoc(token, getTestDoc());
110
            System.out.println("CST: document created.  Id: " + id.getValue());
111
            //get the doc and sysmetadata
112
            System.out.println("CST: getting document with id " + id.getValue());
113
            String gotDoc = getDoc(token, id);
114
            System.out.println("CST: getting sysmeta for doc with id " + id.getValue());
115
            SystemMetadata sm = getSystemMetadata(token, id);
116
            //update the doc
117
            System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ doing the update now $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
118
            gotDoc = gotDoc.replaceAll("XXX", "YYY");
119
            System.out.println("CST: Changed test doc to " + gotDoc);
120
            Identifier newid = new Identifier();
121
            newid.setValue(generateDocumentId());
122
            System.out.println("CST: Generated newid " + newid);
123
            StringBufferInputStream sbis = new StringBufferInputStream(gotDoc);
124
            SystemMetadata newsm = createSystemMetadata(newid, gotDoc);
125
            System.out.println("CST: Created system metadata for new doc...updating.");
126
            Identifier updatedid = cs.update(token, newid, sbis, id, newsm);
127
            System.out.println("CST: Called update. Returned id " + id);
128
            //get doc - check that it matches update
129
            String newdoc = getDoc(token, newid);
130
            assertTrue(gotDoc.equals(newdoc));
131
            //get sysmeta - check that ids and other fields are updated
132
            SystemMetadata newnewsm = getSystemMetadata(token, id);
133
            List obsoletedByList = newnewsm.getObsoletedByList();
134
            assertTrue(obsoletedByList.size() == 1);
135
            String obsBy = ((Identifier)obsoletedByList.get(0)).getValue();
136
            assertTrue(obsBy.equals(id.getValue()));
137
        }
138
        catch(Exception e)
139
        {
140
            e.printStackTrace();
141
            fail("Error in testUpdate: " + e.getMessage());
142
        }
143
	}
144
	
145
	/**
146
	 * public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
147
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
148
     *       InvalidRequest, NotImplemented
149
	 */
150
	public void testGetSystemMetadata()
151
	{
152
	    printTestHeader("testGetSystemMetadata");
153
	    try
154
	    {
155
            CrudService cs = CrudService.getInstance();
156
            AuthToken token = getToken();
157
            //run create
158
            Identifier id = createDoc(token, getTestDoc());
159
            //get the systemMetadata and make sure it is the correct object for this testDoc
160
            SystemMetadata sm = getSystemMetadata(token, id);
161
            assertTrue(sm.getIdentifier().getValue().equals(id.getValue()));
162
            assertTrue(sm.getChecksum().getValue().equals(checksum(getTestDoc())));
163
            
164
            try
165
            {
166
                Identifier fakeid = new Identifier();
167
                fakeid.setValue("somethingfake.234234");
168
                getSystemMetadata(token, fakeid);
169
                fail("getSystemMetadata should have thrown an exception.");
170
            }
171
            catch(Exception e)
172
            {
173
                assertTrue(true);
174
            }
175
        }
176
        catch(Exception e)
177
        {
178
            e.printStackTrace();
179
            fail("Error testing system metadata: " + e.getMessage());
180
        }
181
	}
182
	
183
	/**
184
	 * create(AuthToken token, Identifier guid, InputStream object, SystemMetadata sysmeta) 
185
     *   throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
186
     *       InsufficientResources, InvalidSystemMetadata, NotImplemented
187
     *
188
     * public InputStream get(AuthToken token, Identifier guid)
189
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
190
     *       NotImplemented
191
	 */
192
	public void testCreateAndGet()
193
	{
194
	    printTestHeader("testCreateAndGet");
195
	    try
196
	    {
197
	        CrudService cs = CrudService.getInstance();
198
	        AuthToken token = getToken();
199
	        //run create
200
	        Identifier id = createDoc(token, getTestDoc());
201
	        //run get
202
            String gotDoc = getDoc(token, id);
203
            System.out.println("got doc: " + gotDoc);
204
            //compare the docs
205
            assertTrue(gotDoc.trim().equals(getTestDoc().trim()));
206
            
207
            try
208
            {
209
                Identifier fakeid = new Identifier();
210
                fakeid.setValue("somethingfake.234234");
211
                getDoc(token, fakeid);
212
                fail("testCreateAndGet should have thrown an exception.");
213
            }
214
            catch(Exception e)
215
            {
216
                assertTrue(true);
217
            }
218
        }
219
        catch(Exception e)
220
        {
221
            e.printStackTrace();
222
            fail("Error in testCreate: " + e.getMessage());
223
        }
224
	}
225

    
226
	/**
227
	 * getInstance()
228
	 */
229
	public void testSingletonAccessor()
230
	{
231
	    printTestHeader("testSingletonAccessor");
232
	    CrudService cs = CrudService.getInstance();
233
	    assertNotNull(cs);
234
	}
235
	
236
	/**
237
	 * Run an initial test that always passes to check that the test harness is
238
	 * working.
239
	 */
240
	public void initialize() 
241
	{
242
	    printTestHeader("initialize");
243
		assertTrue(1 == 1);
244
	}
245
	
246
	/**
247
	 * return the systemMetadata object for id
248
	 */
249
	private SystemMetadata getSystemMetadata(AuthToken token, Identifier id)
250
	  throws Exception
251
	{
252
	    System.out.println("getting system metadata for id: " + id.getValue());
253
	    CrudService cs = CrudService.getInstance();
254
	    return cs.getSystemMetadata(token, id);
255
	}
256
	
257
	/**
258
	 * get a doc from metacat using CrudService.get()
259
	 */
260
	private String getDoc(AuthToken token, Identifier id)
261
	  throws Exception
262
	{
263
	    System.out.println("getting doc for id " + id.getValue());
264
	    CrudService cs = CrudService.getInstance();
265
	    //try to get the same doc then compare them
266
        InputStream gotDocStream = cs.get(token, id);
267
        StringBuffer sb = new StringBuffer();
268
        byte[] b = new byte[1024];
269
        int numread = gotDocStream.read(b, 0, 1024);
270
        while(numread != -1)
271
        {
272
            sb.append(new String(b, 0, numread));
273
            numread = gotDocStream.read(b, 0, 1024);
274
        }
275
        System.out.println("returning doc for id " + id.getValue());
276
        return sb.toString();
277
	}
278
	
279
	/**
280
	 * return a test document
281
	 */
282
	private String getTestDoc()
283
	{
284
	    return "<?xml version=\"1.0\"?><test><somecontent>This is some content XXX</somecontent></test>\n";
285
	}
286
	
287
	/**
288
	 * authenticate and return a token
289
	 */
290
	private AuthToken getToken()
291
	  throws Exception
292
	{
293
	    CrudService cs = CrudService.getInstance();
294
        //login and get a sessionid
295
        System.out.println("creating MetacatRestClient with url " + cs.getContextUrl());
296
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
297
        String username = PropertyService.getProperty("test.mcUser");
298
        String password = PropertyService.getProperty("test.mcPassword");
299
        System.out.println("logging in with username: " + username + " and password " + password + " to context " + cs.getContextUrl());
300
        String response = restClient.login(username, password);
301
        //System.out.println("response to login: " + response);
302
        String sessionid = restClient.getSessionId();
303
        SessionService sessionService = SessionService.getInstance();
304
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
305
        System.out.println("sessionid: " + sessionid);
306
        AuthToken token = new AuthToken(sessionid);
307
        return token;
308
	}
309
	
310
	/**
311
	 * create a doc using CrudService.create() and return its id
312
	 */
313
	private Identifier createDoc(AuthToken token, String testDoc) throws Exception
314
	{
315
	    Identifier id;
316
        CrudService cs = CrudService.getInstance();
317
        
318
        id = new Identifier();
319
        String docid = generateDocumentId();
320
        id.setValue(docid);
321
        System.out.println("creating doc with id " + id.getValue());            
322
        
323
        //create the system metadata then run the create method
324
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
325
        SystemMetadata sm = createSystemMetadata(id, testDoc);
326
        //create the doc
327
        cs.create(token, id, sbis, sm);
328
        System.out.println("document with id " + id.getValue() + " created.");
329
        return id;
330
	}
331
	
332
	/**
333
	 * create a generic SystemMetadata object for testing
334
	 */
335
	private SystemMetadata createSystemMetadata(Identifier id, String testDoc)
336
	  throws Exception
337
	{
338
	    SystemMetadata sm = new SystemMetadata();
339
        //set the id
340
        System.out.println("creating system metadata object for document with id " + id.getValue());
341
        sm.setIdentifier(id);
342
        System.out.println("sm id is " + id.getValue());
343
        sm.setObjectFormat(ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
344
        System.out.println("sm objectformat: " + sm.getObjectFormat());
345
        //create the checksum
346
        String checksumS = checksum(testDoc);
347
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
348
        Checksum checksum = new Checksum();
349
        checksum.setValue(checksumS);
350
        checksum.setAlgorithm(ca);
351
        sm.setChecksum(checksum);
352
        System.out.println("sm checksum is " + checksumS);
353
        //set the size
354
        sm.setSize(testDoc.getBytes().length);
355
        System.out.println("sm size: " + testDoc.getBytes().length);
356
        //submitter
357
        Principal p = new Principal();
358
        p.setValue("joe");
359
        sm.setSubmitter(p);
360
        sm.setRightsHolder(p);
361
        sm.setDateUploaded(new Date());
362
        sm.setDateSysMetadataModified(new Date());
363
        NodeReference nr = new NodeReference();
364
        nr.setValue("metacat");
365
        sm.setOriginMemberNode(nr);
366
        sm.setAuthoritativeMemberNode(nr);
367
        return sm;
368
	}
369
	
370
	/**
371
	 * print a header to start each test
372
	 */
373
	private void printTestHeader(String testName)
374
	{
375
	    System.out.println();
376
	    System.out.println("********************************** " + testName + " **********************************");
377
	}
378
  
379
	/**
380
	 * produce an md5 checksum for item
381
	 */
382
	private String checksum(String item)
383
	  throws Exception
384
	{
385
        StringBufferInputStream fis =  new StringBufferInputStream(item);
386
        
387
        byte[] buffer = new byte[1024];
388
        MessageDigest complete = MessageDigest.getInstance("MD5");
389
        int numRead;
390
        
391
        do 
392
        {
393
          numRead = fis.read(buffer);
394
          if (numRead > 0) 
395
          {
396
            complete.update(buffer, 0, numRead);
397
          }
398
        } while (numRead != -1);
399
        
400
        
401
        return getHex(complete.digest());
402
	}
403
	
404
	/**
405
	 * convert a byte array to a hex string
406
	 */
407
	private static String getHex( byte [] raw ) 
408
	{
409
	    final String HEXES = "0123456789ABCDEF";
410
        if ( raw == null ) {
411
          return null;
412
        }
413
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
414
        for ( final byte b : raw ) {
415
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
416
             .append(HEXES.charAt((b & 0x0F)));
417
        }
418
        return hex.toString();
419
    }
420
}
    (1-1/1)