Project

General

Profile

1 5335 berkley
/**
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 5337 berkley
import java.security.MessageDigest;
32
33 5335 berkley
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 5337 berkley
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 5335 berkley
/**
50
 * A JUnit test for testing the dataone CrudService class
51
 */
52
public class CrudServiceTest extends MCTestCase
53 5340 berkley
{
54
    /**
55
    * consstructor for the test
56
    */
57
    public CrudServiceTest(String name)
58
    {
59
        super(name);
60
        init();
61
    }
62 5335 berkley
63 5340 berkley
    /**
64 5335 berkley
	 * Establish a testing framework by initializing appropriate objects
65
	 */
66
	public void setUp() throws Exception
67
	{
68
		super.setUp();
69
	}
70
71
	/**
72
	 * Release any objects after tests are complete
73
	 */
74
	public void tearDown()
75
	{
76
	}
77 5340 berkley
78
	public void init()
79
	{
80
	    try
81
	    {
82
83
        }
84
        catch(Exception e)
85
        {
86
            e.printStackTrace();
87
            fail("Could not initialize CrudServiceTest: " + e.getMessage());
88
        }
89
	}
90 5335 berkley
91
	/**
92
	 * Create a suite of tests to be run together
93
	 */
94
	public static Test suite()
95
	{
96
		TestSuite suite = new TestSuite();
97 5346 berkley
		suite.addTest(new CrudServiceTest("initialize"));
98 5337 berkley
		suite.addTest(new CrudServiceTest("testSingletonAccessor"));
99 5346 berkley
		suite.addTest(new CrudServiceTest("testCreateAndGet"));
100 5341 berkley
		suite.addTest(new CrudServiceTest("testGetSystemMetadata"));
101 5337 berkley
		//suite.addTest(new CrudServiceTest(""));
102
		//suite.addTest(new CrudServiceTest(""));
103
		//suite.addTest(new CrudServiceTest(""));
104 5335 berkley
		return suite;
105
	}
106 5337 berkley
107
	/**
108 5341 berkley
	 * public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
109
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
110
     *       InvalidRequest, NotImplemented
111
	 */
112
	public void testGetSystemMetadata()
113
	{
114 5344 berkley
	    printTestHeader("testGetSystemMetadata");
115
	    try
116
	    {
117
            CrudService cs = CrudService.getInstance();
118
            AuthToken token = getToken();
119
            //run create
120
            Identifier id = createDoc(token, getTestDoc());
121
            //get the systemMetadata and make sure it is the correct object for this testDoc
122
            SystemMetadata sm = getSystemMetadata(token, id);
123
            assertTrue(sm.getIdentifier().getValue().equals(id.getValue()));
124
            assertTrue(sm.getChecksum().getValue().equals(checksum(getTestDoc())));
125
        }
126
        catch(Exception e)
127
        {
128
            e.printStackTrace();
129
            fail("Error testing system metadata: " + e.getMessage());
130
        }
131 5341 berkley
	}
132
133
	/**
134 5337 berkley
	 * create(AuthToken token, Identifier guid, InputStream object, SystemMetadata sysmeta)
135
     *   throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
136
     *       InsufficientResources, InvalidSystemMetadata, NotImplemented
137 5340 berkley
     *
138
     * public InputStream get(AuthToken token, Identifier guid)
139
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound,
140
     *       NotImplemented
141 5337 berkley
	 */
142 5340 berkley
	public void testCreateAndGet()
143 5337 berkley
	{
144 5344 berkley
	    printTestHeader("testCreateAndGet");
145 5337 berkley
	    try
146
	    {
147 5341 berkley
	        CrudService cs = CrudService.getInstance();
148
	        AuthToken token = getToken();
149
	        //run create
150 5343 berkley
	        Identifier id = createDoc(token, getTestDoc());
151
	        //run get
152 5342 berkley
            String gotDoc = getDoc(token, id);
153 5340 berkley
            System.out.println("got doc: " + gotDoc);
154 5343 berkley
            //compare the docs
155
            assertTrue(gotDoc.trim().equals(getTestDoc().trim()));
156 5337 berkley
        }
157
        catch(Exception e)
158
        {
159
            e.printStackTrace();
160
            fail("Error in testCreate: " + e.getMessage());
161
        }
162
	}
163 5335 berkley
164
	/**
165 5337 berkley
	 * getInstance()
166
	 */
167
	public void testSingletonAccessor()
168
	{
169 5344 berkley
	    printTestHeader("testSingletonAccessor");
170 5337 berkley
	    CrudService cs = CrudService.getInstance();
171
	    assertNotNull(cs);
172
	}
173
174
	/**
175 5335 berkley
	 * Run an initial test that always passes to check that the test harness is
176
	 * working.
177
	 */
178
	public void initialize()
179
	{
180 5344 berkley
	    printTestHeader("initialize");
181 5335 berkley
		assertTrue(1 == 1);
182
	}
183 5341 berkley
184 5342 berkley
	/**
185 5344 berkley
	 * return the systemMetadata object for id
186
	 */
187
	private SystemMetadata getSystemMetadata(AuthToken token, Identifier id)
188
	  throws Exception
189
	{
190
	    System.out.println("getting system metadata for id: " + id.getValue());
191
	    CrudService cs = CrudService.getInstance();
192
	    return cs.getSystemMetadata(token, id);
193
	}
194
195
	/**
196 5342 berkley
	 * get a doc from metacat using CrudService.get()
197
	 */
198
	private String getDoc(AuthToken token, Identifier id)
199
	  throws Exception
200
	{
201 5344 berkley
	    System.out.println("getting doc for id " + id.getValue());
202 5342 berkley
	    CrudService cs = CrudService.getInstance();
203
	    //try to get the same doc then compare them
204
        InputStream gotDocStream = cs.get(token, id);
205
        StringBuffer sb = new StringBuffer();
206
        byte[] b = new byte[1024];
207
        int numread = gotDocStream.read(b, 0, 1024);
208
        while(numread != -1)
209
        {
210
            sb.append(new String(b, 0, numread));
211
            numread = gotDocStream.read(b, 0, 1024);
212
        }
213 5344 berkley
        System.out.println("returning doc for id " + id.getValue());
214 5342 berkley
        return sb.toString();
215
	}
216
217
	/**
218
	 * return a test document
219
	 */
220 5341 berkley
	private String getTestDoc()
221
	{
222
	    return "<?xml version=\"1.0\"?><test></test>\n";
223
	}
224
225
	/**
226
	 * authenticate and return a token
227
	 */
228
	private AuthToken getToken()
229
	  throws Exception
230
	{
231
	    CrudService cs = CrudService.getInstance();
232
        //login and get a sessionid
233
        System.out.println("creating MetacatRestClient with url " + cs.getContextUrl());
234
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
235
        String username = PropertyService.getProperty("test.mcUser");
236
        String password = PropertyService.getProperty("test.mcPassword");
237
        System.out.println("logging in with username: " + username + " and password " + password + " to context " + cs.getContextUrl());
238
        String response = restClient.login(username, password);
239
        //System.out.println("response to login: " + response);
240
        String sessionid = restClient.getSessionId();
241
        SessionService sessionService = SessionService.getInstance();
242
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
243
        System.out.println("sessionid: " + sessionid);
244
        AuthToken token = new AuthToken(sessionid);
245
        return token;
246
	}
247
248
	/**
249 5342 berkley
	 * create a doc using CrudService.create() and return its id
250 5341 berkley
	 */
251 5343 berkley
	private Identifier createDoc(AuthToken token, String testDoc) throws Exception
252 5341 berkley
	{
253
	    Identifier id;
254
        CrudService cs = CrudService.getInstance();
255
256
        id = new Identifier();
257
        String docid = generateDocumentId();
258
        id.setValue(docid);
259 5344 berkley
        System.out.println("creating doc with id " + id.getValue());
260
261 5341 berkley
        //create the system metadata then run the create method
262
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
263
        SystemMetadata sm = new SystemMetadata();
264
        //set the id
265 5344 berkley
        System.out.println("creating system metadata object for document with id " + id.getValue());
266 5341 berkley
        sm.setIdentifier(id);
267
        System.out.println("sm id is " + id.getValue());
268
        sm.setObjectFormat(ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
269
        System.out.println("sm objectformat: " + sm.getObjectFormat());
270
        //create the checksum
271
        String checksumS = checksum(testDoc);
272
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
273
        Checksum checksum = new Checksum();
274
        checksum.setValue(checksumS);
275
        checksum.setAlgorithm(ca);
276
        sm.setChecksum(checksum);
277
        System.out.println("sm checksum is " + checksumS);
278
        //set the size
279
        sm.setSize(testDoc.getBytes().length);
280
        System.out.println("sm size: " + testDoc.getBytes().length);
281
        //submitter
282
        Principal p = new Principal();
283
        p.setValue("joe");
284
        sm.setSubmitter(p);
285
        sm.setRightsHolder(p);
286
        sm.setDateUploaded(new Date());
287
        sm.setDateSysMetadataModified(new Date());
288
        NodeReference nr = new NodeReference();
289
        nr.setValue("metacat");
290
        sm.setOriginMemberNode(nr);
291
        sm.setAuthoritativeMemberNode(nr);
292
        //create the doc
293
        cs.create(token, id, sbis, sm);
294 5344 berkley
        System.out.println("document with id " + id.getValue() + " created.");
295 5341 berkley
        return id;
296
	}
297 5344 berkley
298
	/**
299
	 * print a header to start each test
300
	 */
301
	private void printTestHeader(String testName)
302
	{
303
	    System.out.println();
304
	    System.out.println("********************************** " + testName + " **********************************");
305
	}
306 5335 berkley
307 5337 berkley
	/**
308
	 * produce an md5 checksum for item
309
	 */
310
	private String checksum(String item)
311
	  throws Exception
312
	{
313
        StringBufferInputStream fis =  new StringBufferInputStream(item);
314
315
        byte[] buffer = new byte[1024];
316
        MessageDigest complete = MessageDigest.getInstance("MD5");
317
        int numRead;
318
319
        do
320
        {
321
          numRead = fis.read(buffer);
322
          if (numRead > 0)
323
          {
324
            complete.update(buffer, 0, numRead);
325
          }
326
        } while (numRead != -1);
327
328
329
        return getHex(complete.digest());
330
	}
331
332
	/**
333
	 * convert a byte array to a hex string
334
	 */
335
	private static String getHex( byte [] raw )
336
	{
337
	    final String HEXES = "0123456789ABCDEF";
338
        if ( raw == null ) {
339
          return null;
340
        }
341
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
342
        for ( final byte b : raw ) {
343
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
344
             .append(HEXES.charAt((b & 0x0F)));
345
        }
346
        return hex.toString();
347
    }
348 5335 berkley
}