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
        init();
61
    }
62
  
63
    /**
64
	 * 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
	
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

    
91
	/**
92
	 * Create a suite of tests to be run together
93
	 */
94
	public static Test suite() 
95
	{
96
		TestSuite suite = new TestSuite();
97
		suite.addTest(new CrudServiceTest("initialize"));
98
		suite.addTest(new CrudServiceTest("testSingletonAccessor"));
99
		suite.addTest(new CrudServiceTest("testCreateAndGet"));
100
		suite.addTest(new CrudServiceTest("testGetSystemMetadata"));
101
		//suite.addTest(new CrudServiceTest(""));
102
		//suite.addTest(new CrudServiceTest(""));
103
		//suite.addTest(new CrudServiceTest(""));
104
		return suite;
105
	}
106
	
107
	/**
108
	 * public SystemMetadata getSystemMetadata(AuthToken token, Identifier guid)
109
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
110
     *       InvalidRequest, NotImplemented
111
	 */
112
	public void testGetSystemMetadata()
113
	{
114
	    
115
	}
116
	
117
	/**
118
	 * create(AuthToken token, Identifier guid, InputStream object, SystemMetadata sysmeta) 
119
     *   throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType, 
120
     *       InsufficientResources, InvalidSystemMetadata, NotImplemented
121
     *
122
     * public InputStream get(AuthToken token, Identifier guid)
123
     *       throws InvalidToken, ServiceFailure, NotAuthorized, NotFound, 
124
     *       NotImplemented
125
	 */
126
	public void testCreateAndGet()
127
	{
128
	    try
129
	    {
130
	        String testDoc = getTestDoc();
131
	        CrudService cs = CrudService.getInstance();
132
	        AuthToken token = getToken();
133
	        //run create
134
	        Identifier id = createDoc(token);
135
            String gotDoc = getDoc(token, id);
136
            System.out.println("got doc: " + gotDoc);
137
            assertTrue(gotDoc.trim().equals(testDoc.trim()));
138
        }
139
        catch(Exception e)
140
        {
141
            e.printStackTrace();
142
            fail("Error in testCreate: " + e.getMessage());
143
        }
144
	}
145

    
146
	/**
147
	 * getInstance()
148
	 */
149
	public void testSingletonAccessor()
150
	{
151
	    CrudService cs = CrudService.getInstance();
152
	    assertNotNull(cs);
153
	}
154
	
155
	/**
156
	 * Run an initial test that always passes to check that the test harness is
157
	 * working.
158
	 */
159
	public void initialize() 
160
	{
161
		assertTrue(1 == 1);
162
	}
163
	
164
	/**
165
	 * get a doc from metacat using CrudService.get()
166
	 */
167
	private String getDoc(AuthToken token, Identifier id)
168
	  throws Exception
169
	{
170
	    CrudService cs = CrudService.getInstance();
171
	    //try to get the same doc then compare them
172
        InputStream gotDocStream = cs.get(token, id);
173
        StringBuffer sb = new StringBuffer();
174
        byte[] b = new byte[1024];
175
        int numread = gotDocStream.read(b, 0, 1024);
176
        while(numread != -1)
177
        {
178
            sb.append(new String(b, 0, numread));
179
            numread = gotDocStream.read(b, 0, 1024);
180
        }
181
        
182
        return sb.toString();
183
	}
184
	
185
	/**
186
	 * return a test document
187
	 */
188
	private String getTestDoc()
189
	{
190
	    return "<?xml version=\"1.0\"?><test></test>\n";
191
	}
192
	
193
	/**
194
	 * authenticate and return a token
195
	 */
196
	private AuthToken getToken()
197
	  throws Exception
198
	{
199
	    CrudService cs = CrudService.getInstance();
200
        //login and get a sessionid
201
        System.out.println("creating MetacatRestClient with url " + cs.getContextUrl());
202
        MetacatRestClient restClient = new MetacatRestClient(cs.getContextUrl());
203
        String username = PropertyService.getProperty("test.mcUser");
204
        String password = PropertyService.getProperty("test.mcPassword");
205
        System.out.println("logging in with username: " + username + " and password " + password + " to context " + cs.getContextUrl());
206
        String response = restClient.login(username, password);
207
        //System.out.println("response to login: " + response);
208
        String sessionid = restClient.getSessionId();
209
        SessionService sessionService = SessionService.getInstance();
210
        sessionService.registerSession(new SessionData(sessionid, username, new String[0], password, "CrudServiceLogin"));
211
        System.out.println("sessionid: " + sessionid);
212
        AuthToken token = new AuthToken(sessionid);
213
        return token;
214
	}
215
	
216
	/**
217
	 * create a doc using CrudService.create() and return its id
218
	 */
219
	private Identifier createDoc(AuthToken token) throws Exception
220
	{
221
	    Identifier id;
222
        CrudService cs = CrudService.getInstance();
223
        String testDoc = getTestDoc();
224
        
225
        id = new Identifier();
226
        String docid = generateDocumentId();
227
        id.setValue(docid);
228
                    
229
        //create the system metadata then run the create method
230
        StringBufferInputStream sbis = new StringBufferInputStream(testDoc);
231
        SystemMetadata sm = new SystemMetadata();
232
        //set the id
233
        sm.setIdentifier(id);
234
        System.out.println("sm id is " + id.getValue());
235
        sm.setObjectFormat(ObjectFormat.convert("eml://ecoinformatics.org/eml-2.1.0"));
236
        System.out.println("sm objectformat: " + sm.getObjectFormat());
237
        //create the checksum
238
        String checksumS = checksum(testDoc);
239
        ChecksumAlgorithm ca = ChecksumAlgorithm.convert("MD5");
240
        Checksum checksum = new Checksum();
241
        checksum.setValue(checksumS);
242
        checksum.setAlgorithm(ca);
243
        sm.setChecksum(checksum);
244
        System.out.println("sm checksum is " + checksumS);
245
        //set the size
246
        sm.setSize(testDoc.getBytes().length);
247
        System.out.println("sm size: " + testDoc.getBytes().length);
248
        //submitter
249
        Principal p = new Principal();
250
        p.setValue("joe");
251
        sm.setSubmitter(p);
252
        sm.setRightsHolder(p);
253
        sm.setDateUploaded(new Date());
254
        sm.setDateSysMetadataModified(new Date());
255
        NodeReference nr = new NodeReference();
256
        nr.setValue("metacat");
257
        sm.setOriginMemberNode(nr);
258
        sm.setAuthoritativeMemberNode(nr);
259
        //create the doc
260
        cs.create(token, id, sbis, sm);
261
        return id;
262
	}
263
  
264
	/**
265
	 * produce an md5 checksum for item
266
	 */
267
	private String checksum(String item)
268
	  throws Exception
269
	{
270
        StringBufferInputStream fis =  new StringBufferInputStream(item);
271
        
272
        byte[] buffer = new byte[1024];
273
        MessageDigest complete = MessageDigest.getInstance("MD5");
274
        int numRead;
275
        
276
        do 
277
        {
278
          numRead = fis.read(buffer);
279
          if (numRead > 0) 
280
          {
281
            complete.update(buffer, 0, numRead);
282
          }
283
        } while (numRead != -1);
284
        
285
        
286
        return getHex(complete.digest());
287
	}
288
	
289
	/**
290
	 * convert a byte array to a hex string
291
	 */
292
	private static String getHex( byte [] raw ) 
293
	{
294
	    final String HEXES = "0123456789ABCDEF";
295
        if ( raw == null ) {
296
          return null;
297
        }
298
        final StringBuilder hex = new StringBuilder( 2 * raw.length );
299
        for ( final byte b : raw ) {
300
          hex.append(HEXES.charAt((b & 0xF0) >> 4))
301
             .append(HEXES.charAt((b & 0x0F)));
302
        }
303
        return hex.toString();
304
    }
305
}
    (1-1/1)