Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author: Serhan AKIN $'
7
 *     '$Date: 2009-07-15 10:54:27 +0300  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
package edu.ucsb.nceas.metacattest.restservice;
24

    
25
import java.io.IOException;
26
import java.io.Reader;
27
import java.io.StringReader;
28
import java.util.Vector;
29

    
30
import junit.framework.Test;
31
import junit.framework.TestSuite;
32
import edu.ucsb.nceas.MCTestCase;
33
import edu.ucsb.nceas.metacat.IdentifierManager;
34
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
35
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
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.client.rest.MetacatRest;
40
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
41
import edu.ucsb.nceas.metacat.properties.PropertyService;
42
import edu.ucsb.nceas.utilities.IOUtil;
43
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
44

    
45
/**
46
 * A JUnit test for testing Step class processing
47
 */
48
public class MetacatRestClientTest extends MCTestCase{
49
	protected static String contextUrl;
50
	static {
51
		try {
52
		    contextUrl = PropertyService.getProperty("test.contextUrl");
53
			username = PropertyService.getProperty("test.mcUser");
54
			password = PropertyService.getProperty("test.mcPassword");
55
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
56
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
57
		} catch (PropertyNotFoundException pnfe) {
58
			System.err.println("Could not get property in static block: " 
59
					+ pnfe.getMessage());
60
		}
61
	}
62
	
63
    private String failpass = "sdfsdfsdfsd";
64
    private MetacatRest m;
65
    private static final String DOC_TITLE = "Test MetacatRest service";    
66
    
67
    /**
68
     * Constructor to build the test
69
     *
70
     * @param name the name of the test method
71
     */
72
    public MetacatRestClientTest(String name)
73
    {
74
        super(name);
75
    }
76

    
77
    /**
78
     * Establish a testing framework by initializing appropriate objects
79
     */
80
    public void setUp()
81
    {
82
        m = new MetacatRestClient(contextUrl);
83
    }
84
    
85
    /**
86
     * Release any objects after tests are complete
87
     */
88
    public void tearDown()
89
    {
90
    }
91

    
92
    /**
93
     * Create a suite of tests to be run together
94
     */
95
    public static Test suite()
96
    {
97
      TestSuite suite = new TestSuite();
98
      suite.addTest(new MetacatRestClientTest("initialize"));
99
      suite.addTest(new MetacatRestClientTest("invalidLogin"));
100
      suite.addTest(new MetacatRestClientTest("login"));
101
      suite.addTest(new MetacatRestClientTest("logout"));
102
      suite.addTest(new MetacatRestClientTest("get"));
103
      suite.addTest(new MetacatRestClientTest("invalidGet"));
104
      suite.addTest(new MetacatRestClientTest("getPrivate"));
105
      suite.addTest(new MetacatRestClientTest("authenticatedGet"));
106
      suite.addTest(new MetacatRestClientTest("query"));
107
      suite.addTest(new MetacatRestClientTest("authenticatedQuery"));     
108
      suite.addTest(new MetacatRestClientTest("crud"));
109
      suite.addTest(new MetacatRestClientTest("getNextObject"));
110
      suite.addTest(new MetacatRestClientTest("getNextRevision"));
111
      suite.addTest(new MetacatRestClientTest("getAllDocids"));
112
      suite.addTest(new MetacatRestClientTest("isRegistered"));
113
      suite.addTest(new MetacatRestClientTest("addLSID"));
114
      return suite;
115
  }
116
    
117
    
118
    /**
119
     * Run an initial test that always passes to check that the test
120
     * harness is working.
121
     */
122
    public void initialize() 
123
    {
124
        assertTrue(1 == 1);
125
    }
126
    
127
    /**
128
     * Test the login() function with valid credentials
129
     */
130
    public void login()
131
    {
132
        debug("\nStarting login test...");
133
        debug("-------------------------------------------------------");
134
        // Try a valid login
135
        try {
136
            String response = m.login(username, password);
137
            debug("login(): response=" + response);
138
            assertTrue(response != null);
139
            assertTrue(response.indexOf("<login>") != -1);
140
            String sessionId = m.getSessionId();
141
            debug("login(): Session ID=" + m.getSessionId());
142
            assertTrue(sessionId != null);
143
            assertTrue(response.indexOf(m.getSessionId()) != -1);
144
        } catch (MetacatAuthException mae) {
145
            fail("Authorization failed:\n" + mae.getMessage());
146
        } catch (MetacatInaccessibleException mie) {
147
            fail("Metacat Inaccessible:\n" + mie.getMessage());
148
        }
149
    }
150
    
151
    /**
152
     * Test the login() function with INVALID credentials
153
     */
154
    public void invalidLogin()
155
    {
156
        debug("\nStarting invalidLogin test...");
157
        debug("-------------------------------------------------------");
158
        // Try an invalid login
159
        String response = "";
160
        try {
161
        	response = m.login(username, failpass);        	
162
            fail("Authorization should have failed.");
163
        } catch (MetacatAuthException mae) {
164
        	debug("invalid login(): response=" + mae.getMessage());
165
            assertNotNull(mae);
166
        } catch (MetacatInaccessibleException mie) {
167
            fail("Metacat Inaccessible:\n" + mie.getMessage());
168
        } 
169
    }
170
    
171
    /**
172
     * Test the logout() function. 
173
     */
174
    public void logout()
175
    {
176
       debug("\nStarting logout test...");
177
       debug("-------------------------------------------------------");
178
       try {
179
            m.login(username, password);
180
            String response = m.logout();
181
            debug("logout(): Response ="+response);
182
            assertTrue(response.indexOf("<success>") == -1);
183
        } catch (MetacatAuthException mae) {
184
            fail("Authorization failed:\n" + mae.getMessage());
185
        } catch (MetacatInaccessibleException mie) {
186
            fail("Metacat Inaccessible:\n" + mie.getMessage());
187
        } catch (MetacatException me) {
188
            if(me.getMessage().
189
              indexOf("Permission denied for user public inser") == -1){
190
               fail("Metacat Error:\n" + me.getMessage());
191
           }
192
        } catch (Exception e) {
193
            fail("General exception:\n" + e.getMessage());
194
        }
195
    }
196
    
197
    
198
    /**
199
     * Test the get() function with a public document
200
     */
201
    public void get()
202
    {
203
        debug("\nStarting get test...");
204
        debug("-------------------------------------------------------"); 
205
        try {
206
            IdentifierManager im = IdentifierManager.getInstance();
207
            String docid = insertTestDocument();
208
            String guid = "test:"+docid;
209
            im.createMapping(guid, docid);
210
            Reader r =  m.getObject(guid, null);            
211
            String doc = IOUtil.getAsString(r, true);
212
            doc = doc +"\n";
213
            debug("document:\n"+doc);
214
            assertTrue(doc.indexOf(DOC_TITLE) != -1);
215
        } catch (MetacatInaccessibleException mie) {
216
            fail("Metacat Inaccessible:\n" + mie.getMessage());
217
        } catch (Exception e) {
218
            fail("General exception:\n" + e.getMessage());
219
        }
220
    }
221
    
222
    /**
223
     * Test the get() function with a private document
224
     */
225
    public void getPrivate()
226
    {
227
        assertTrue("Not implemented yet.", 1==1);
228
        /*
229
        debug("\nStarting getprivate  test...");
230
        debug("-------------------------------------------------------");        
231
        try {
232
            Reader r =  m.getObject(authorized_doc_id, null);            
233
            String doc = IOUtil.getAsString(r, true);
234
            doc = doc +"\n";
235
            debug("document:\n"+doc);
236
        } catch (MetacatInaccessibleException mie) {
237
            fail("Metacat Inaccessible:\n" + mie.getMessage());
238
        } catch (Exception e) {
239
            fail("General exception:\n" + e.getMessage());
240
        }
241
        */
242
    }
243
    
244
    /**
245
     * Test the authenticatedGet() function with a private document without for a valid session
246
     */
247
    public void authenticatedGet()
248
    {
249
        assertTrue("Not implemented yet.", 1==1);
250
        /*
251
        debug("\nStarting authorizedGet test...");
252
        debug("-------------------------------------------------------");
253
        try {
254
        	m.login(username,password);
255
            Reader r =  m.authenticatedGetObject(authorized_doc_id, null);            
256
            String doc = IOUtil.getAsString(r, true);
257
            doc = doc +"\n";
258
            debug("document:\n"+doc);
259
        } catch (MetacatInaccessibleException mie) {
260
            debug("Metacat Inaccessible:\n" + mie.getMessage());
261
        } catch (Exception e) {
262
            debug("General exception:\n" + e.getMessage());
263
        }
264
        */
265
    }
266
    
267
    /**
268
     * Test the get() function with a not existing document
269
     */
270
    public void invalidGet()
271
    {
272
        debug("\nStarting invalid get test ...");
273
        debug("-------------------------------------------------------");
274
        try {
275
            String unregDocid = generateDocumentId() + ".1";
276
            Reader r =  m.getObject(unregDocid, null);            
277
            String doc = IOUtil.getAsString(r, true);
278
            doc = doc +"\n";
279
            debug("document:\n"+doc);
280
            assertTrue(doc.indexOf("<error>") != -1);
281
        } catch (MetacatInaccessibleException mie) {
282
            debug("Metacat Inaccessible:\n" + mie.getMessage());
283
        } catch (DocumentNotFoundException doe) {
284
        	  debug("Document not found:\n" + doe.getMessage());
285
        } catch (Exception e) {
286
        	e.printStackTrace();
287
            debug("General exception:\n" + e.getMessage());
288
        }
289
    }
290
    
291
    /**
292
     * Test the query() function with a public session
293
     */
294
    public void query()
295
    {
296
        assertTrue("Not implemented yet.", 1==1);
297
        /*
298
    	debug("\nStarting query test ...");
299
        debug("-------------------------------------------------------");
300
    	try {
301
    	 FileReader fr = new FileReader(ecogridQueryFile);   	
302
    	 Reader r = m.query(fr);   
303
         String doc = IOUtil.getAsString(r, true);
304
         doc = doc +"\n";
305
         debug("document:\n"+doc);
306
         
307
        } catch (MetacatInaccessibleException mie) {
308
            fail("Metacat Inaccessible:\n" + mie.getMessage());
309
        } catch (Exception e) {
310
        	e.printStackTrace();
311
            fail("General exception:\n" + e.getMessage());
312
        }
313
        */
314
    }
315
    
316
    
317
    
318
    /**
319
     * Test the authenticatedQuery() function
320
     */
321
    public void authenticatedQuery()
322
    {
323
        assertTrue("Not implemented yet.", 1==1);
324
        /*
325
    	debug("\nStarting authenticatedQuery test ...");
326
        debug("-------------------------------------------------------");
327
    	try {
328
    	 FileReader fr = new FileReader(ecogridQueryFile);	
329
    	 m.login(username,password);
330
    	 Reader r = m.authenticatedQuery(fr);   
331
         String doc = IOUtil.getAsString(r, true);
332
         doc = doc +"\n";
333
         debug("document:\n"+doc);
334
         
335
        } catch (MetacatAuthException mae) {
336
            fail("Authorization failed:\n" + mae.getMessage());
337
        } catch (MetacatInaccessibleException mie) {
338
            fail("Metacat Inaccessible:\n" + mie.getMessage());
339
        } catch (Exception e) {
340
        	e.printStackTrace();
341
            fail("General exception:\n" + e.getMessage());
342
        }
343
        */
344
    }
345
    
346
    /**
347
     * Test the insert,update and delete function
348
     */
349
    public void crud()
350
    {
351
    	debug("\nStarting insert,update,delete document test ...");
352
        debug("-------------------------------------------------------");
353
    	try {
354
    	    String accessBlock = getAccessBlock("public", true, true,
355
                    false, false, false);
356
            String emldoc = getTestEmlDoc("Test MetacatRest service", EML2_1_0, null,
357
                    null, "http://fake.example.com/somedata", null,
358
                    accessBlock, null, null,
359
                    null, null);
360
            String docid = generateDocumentId();
361
            
362
    		StringReader sr = new StringReader(emldoc);	
363
    		m.login(username,password);
364

    
365
    		debug("\nFirst insert the document...");
366
    		String response = m.putObject(docid + ".1",sr,true);
367
    		sr.close();
368
    		debug("response:\n"+response);
369
            assertTrue(response.indexOf("success") != -1);
370
    		
371
    		sr = new StringReader(emldoc);
372
    		debug("\nNow update the document...");
373
    		response = m.putObject(docid + ".2",sr,false);    	 
374
    		debug("response:\n"+response);
375
            assertTrue(response.indexOf("success") != -1);
376
    		sr.close();
377
    		
378
    		Thread.sleep(10000);
379
    		
380
    		debug("\nFinally delete the document...");
381
    		response = m.deleteObject(docid + ".2");  
382
    		debug("response:\n"+response);
383
            assertTrue(response.indexOf("success") != -1);
384

    
385
    	} catch (MetacatAuthException mae) {
386
    		fail("Authorization failed:\n" + mae.getMessage());
387
    	} catch (MetacatInaccessibleException mie) {
388
    		fail("Metacat Inaccessible:\n" + mie.getMessage());
389
    	} catch (Exception e) {
390
    		fail("General exception:\n" + e.getMessage());
391
    	}
392
    }
393

    
394
    
395
    /**
396
     * Get the most recent document id for a given scope and be sure
397
     * that it matches the one we last inserted. Assumes this test is run
398
     * immediately following a successful insert() test.
399
     */
400
    public void getNextObject() 
401
    {
402
        debug("\nStarting getNextObject test...");
403
        debug("-------------------------------------------------------");
404
        try {
405

    
406
            String lastId = m.getNextObject(prefix);
407
            debug("getNextObject(): Last Id=" + lastId);
408

    
409
        } catch (MetacatException me) {
410
            fail("Metacat Error:\n" + me.getMessage());
411
        } catch (Exception e) {
412
            fail("General exception:\n" + e.getMessage());
413
        }
414
    }
415

    
416
    /**
417
     * Get the next revision for a given id. Assumes this test is run
418
     * immediately following a successful insert() test.
419
     */
420
    public void getNextRevision()
421
    {
422
        debug("\nStarting getNextRevision test...");
423
        debug("-------------------------------------------------------");
424
        try {
425
            IdentifierManager im = IdentifierManager.getInstance();
426
            String docid = insertTestDocument();
427
            int rev_id = m.getNextRevision(docid);
428
            debug("NextRevision number is " + rev_id);
429

    
430
        } catch (MetacatException me) {
431
            fail("Metacat Error:\n" + me.getMessage());
432
        } catch (Exception e) {
433
            fail("General exception:\n" + e.getMessage());
434
        }
435
    }
436
    
437
    
438
    /**
439
     * Test getAllDocids function
440
     */
441
    public void getAllDocids() 
442
    {
443
        debug("\nStarting getAllDocids test...");
444
        debug("-------------------------------------------------------");
445
        try {
446

    
447
            Vector<String> vector = m.getAllDocids(prefix);
448
            StringBuffer b = new StringBuffer();
449
            for (String doc_id:vector)
450
            	b.append(doc_id+"\n");
451
            debug("getAllDocids():\n " + b.toString());
452

    
453
        } catch (MetacatException me) {
454
            fail("Metacat Error:\n" + me.getMessage());
455
        } catch (Exception e) {
456
            fail("General exception:\n" + e.getMessage());
457
        }
458
    }
459
    
460
    /**
461
     * Test isRegistered function
462
     */
463
    public void isRegistered() 
464
    {
465
        debug("\nStarting isRegistered test...");
466
        debug("-------------------------------------------------------");
467
        try {
468
            IdentifierManager im = IdentifierManager.getInstance();
469
            String docid = insertTestDocument();
470
            boolean registered = m.isRegistered(docid);
471
            debug("isRegistered(): " + docid + ".1" +" is "+(registered?"":"not ")+"registered");
472
            assertTrue(registered);
473
            String unregDocid = generateDocumentId() + ".1";
474
            registered = m.isRegistered(unregDocid);
475
            debug("isRegistered(): " + unregDocid+" is "+(registered?"":"not ")+"registered");
476
            assertFalse(registered);
477
        } catch (MetacatException me) {
478
            fail("Metacat Error:\n" + me.getMessage());
479
        } catch (Exception e) {
480
            fail("General exception:\n" + e.getMessage());
481
        }
482
    }
483
    
484
    /**
485
     * Test addLSID function
486
     */
487
    public void addLSID() 
488
    {
489
    	  debug("\nStarting addLSID test...");
490
    	  debug("-------------------------------------------------------");
491
          try {
492
              String unregDocid = generateDocumentId() + ".1";
493
        	  String response =  m.addLSID(unregDocid);
494
        	  debug("response:\n"+response);
495
          } catch (MetacatException me) {
496
              fail("Metacat Error:\n" + me.getMessage());
497
          } catch (Exception e) {
498
              fail("General exception:\n" + e.getMessage());
499
          }
500
    }
501
    
502
    /** Insert a test document, returning the docid that was used. */
503
    private String insertTestDocument()
504
    {
505
        String accessBlock = getAccessBlock("public", true, true,
506
                false, false, false);
507
        String emldoc = getTestEmlDoc(DOC_TITLE, EML2_1_0, null,
508
                null, "http://fake.example.com/somedata", null,
509
                accessBlock, null, null,
510
                null, null);
511
        String docid = generateDocumentId() + ".1";
512
        StringReader sr = new StringReader(emldoc);        
513
        String response;
514
        try {
515
            m.login(username,password);
516
            response = m.putObject(docid,sr,true);
517
            debug("response:\n"+response);
518
            assertTrue(response.indexOf("success") != -1);
519
        } catch (InsufficientKarmaException e) {
520
            fail(e.getMessage());
521
        } catch (MetacatException e) {
522
            fail(e.getMessage());
523
        } catch (IOException e) {
524
            fail(e.getMessage());
525
        } catch (MetacatInaccessibleException e) {
526
            fail(e.getMessage());
527
        } catch (MetacatAuthException e) {
528
            fail(e.getMessage());
529
        }
530
        return docid;
531
    }
532
}
    (1-1/1)