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.Calendar;
29
import java.util.Date;
30
import java.util.GregorianCalendar;
31
import java.util.SimpleTimeZone;
32
import java.util.TimeZone;
33
import java.util.Vector;
34

    
35
import junit.framework.Test;
36
import junit.framework.TestSuite;
37
import edu.ucsb.nceas.MCTestCase;
38
import edu.ucsb.nceas.metacat.IdentifierManager;
39
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
40
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
41
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
42
import edu.ucsb.nceas.metacat.client.MetacatException;
43
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
44
import edu.ucsb.nceas.metacat.client.rest.MetacatRest;
45
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
46
import edu.ucsb.nceas.metacat.properties.PropertyService;
47
import edu.ucsb.nceas.utilities.IOUtil;
48
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
49

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

    
82
    /**
83
     * Establish a testing framework by initializing appropriate objects
84
     */
85
    public void setUp()
86
    {
87
        System.out.println("contextUrl: " + contextUrl);
88
        m = new MetacatRestClient(contextUrl);
89
    }
90
    
91
    /**
92
     * Release any objects after tests are complete
93
     */
94
    public void tearDown()
95
    {
96
    }
97

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

    
369
    		debug("\nFirst insert the document...");
370
    		String response = m.create(docid + ".1",sr);
371
    		sr.close();
372
    		debug("response:\n"+response);
373
            assertTrue(response.indexOf("success") != -1);
374
    		
375
            Thread.sleep(5000);
376

    
377
    		sr = new StringReader(emldoc);
378
    		debug("\nNow update the document...");
379
    		response = m.update(docid + ".2",sr);    	 
380
    		debug("response:\n"+response);
381
            assertTrue(response.indexOf("success") != -1);
382
    		sr.close();
383

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

    
393
    /**
394
     * Test the delete function
395
     */
396
    public void delete()
397
    {
398
        debug("\nStarting delete document test ...");
399
        debug("-------------------------------------------------------");
400
        try {
401
            String guid = insertTestDocument();
402
            try {
403
                Thread.sleep(5000);
404
            } catch (InterruptedException e) {
405
                debug("Thread.sleep() failed to execute.");
406
            }
407

    
408
            debug("\nDelete the document...");
409
            String response = m.deleteObject(guid);  
410
            debug("response:\n"+response);
411
            assertTrue(response.indexOf("success") != -1);
412
            
413
        } catch (MetacatInaccessibleException mie) {
414
            fail("Metacat Inaccessible:\n" + mie.getMessage());
415
        } catch (InsufficientKarmaException e) {
416
            fail("not Authorized:\n" + e.getMessage());
417
        } catch (MetacatException e) {
418
            fail("Metacat error:\n" + e.getMessage());
419
        }
420
    }
421
    
422
    /**
423
     * Get the most recent document id for a given scope and be sure
424
     * that it matches the one we last inserted. Assumes this test is run
425
     * immediately following a successful insert() test.
426
     */
427
    public void getNextObject() 
428
    {
429
        debug("\nStarting getNextObject test...");
430
        debug("-------------------------------------------------------");
431
        try {
432

    
433
            String lastId = m.getNextObject(prefix);
434
            debug("getNextObject(): Last Id=" + lastId);
435

    
436
        } catch (MetacatException me) {
437
            fail("Metacat Error:\n" + me.getMessage());
438
        } catch (Exception e) {
439
            fail("General exception:\n" + e.getMessage());
440
        }
441
    }
442

    
443
    /**
444
     * Get the next revision for a given id. Assumes this test is run
445
     * immediately following a successful insert() test.
446
     */
447
    public void getNextRevision()
448
    {
449
        debug("\nStarting getNextRevision test...");
450
        debug("-------------------------------------------------------");
451
        try {
452
            IdentifierManager im = IdentifierManager.getInstance();
453
            String docid = insertTestDocument();
454
            int rev_id = m.getNextRevision(docid);
455
            debug("NextRevision number is " + rev_id);
456

    
457
        } catch (MetacatException me) {
458
            fail("Metacat Error:\n" + me.getMessage());
459
        } catch (Exception e) {
460
            fail("General exception:\n" + e.getMessage());
461
        }
462
    }
463
    
464
    
465
    /**
466
     * Test getAllDocids function
467
     */
468
    public void getAllDocids() 
469
    {
470
        debug("\nStarting getAllDocids test...");
471
        debug("-------------------------------------------------------");
472
        try {
473

    
474
            Vector<String> vector = m.getAllDocids(prefix);
475
            StringBuffer b = new StringBuffer();
476
            for (String doc_id:vector)
477
            	b.append(doc_id+"\n");
478
            debug("getAllDocids():\n " + b.toString());
479

    
480
        } catch (MetacatException me) {
481
            fail("Metacat Error:\n" + me.getMessage());
482
        } catch (Exception e) {
483
            fail("General exception:\n" + e.getMessage());
484
        }
485
    }
486
    
487
    /**
488
     * Test isRegistered function
489
     */
490
    public void isRegistered() 
491
    {
492
        debug("\nStarting isRegistered test...");
493
        debug("-------------------------------------------------------");
494
        try {
495
            IdentifierManager im = IdentifierManager.getInstance();
496
            String docid = insertTestDocument();
497
            boolean registered = m.isRegistered(docid);
498
            debug("isRegistered(): " + docid + ".1" +" is "+(registered?"":"not ")+"registered");
499
            assertTrue(registered);
500
            String unregDocid = generateDocumentId() + ".1";
501
            registered = m.isRegistered(unregDocid);
502
            debug("isRegistered(): " + unregDocid+" is "+(registered?"":"not ")+"registered");
503
            assertFalse(registered);
504
        } catch (MetacatException me) {
505
            fail("Metacat Error:\n" + me.getMessage());
506
        } catch (Exception e) {
507
            fail("General exception:\n" + e.getMessage());
508
        }
509
    }
510
    
511
    /**
512
     * Test addLSID function
513
     */
514
    public void addLSID() 
515
    {
516
    	  debug("\nStarting addLSID test...");
517
    	  debug("-------------------------------------------------------");
518
          try {
519
              String unregDocid = generateDocumentId() + ".1";
520
        	  String response =  m.addLSID(unregDocid);
521
        	  debug("response:\n"+response);
522
          } catch (MetacatException me) {
523
              fail("Metacat Error:\n" + me.getMessage());
524
          } catch (Exception e) {
525
              fail("General exception:\n" + e.getMessage());
526
          }
527
    }
528
    
529
    /** Insert a test document, returning the identifier that was used. */
530
    private String insertTestDocument()
531
    {
532
        String accessBlock = getAccessBlock("public", true, true,
533
                false, false, false);
534
        String emldoc = getTestEmlDoc(DOC_TITLE, EML2_1_0, null,
535
                null, "http://fake.example.com/somedata", null,
536
                accessBlock, null, null,
537
                null, null);
538
        //String docid = generateDocumentId() + ".1";
539
        String guid = "testid:" + generateTimeString();
540
        StringReader sr = new StringReader(emldoc);        
541
        String response;
542
        try {
543
            m.login(username,password);
544
            response = m.create(guid, sr);
545
            debug("response:\n"+response);
546
            assertTrue(response.indexOf("success") != -1);
547
        } catch (InsufficientKarmaException e) {
548
            fail(e.getMessage());
549
        } catch (MetacatException e) {
550
            fail(e.getMessage());
551
        } catch (IOException e) {
552
            fail(e.getMessage());
553
        } catch (MetacatInaccessibleException e) {
554
            fail(e.getMessage());
555
        } catch (MetacatAuthException e) {
556
            fail(e.getMessage());
557
        }
558
        return guid;
559
    }
560
    
561
    /** Generate a timestamp for use in IDs. */
562
    private String generateTimeString()
563
    {
564
        StringBuffer guid = new StringBuffer();
565

    
566
        // Create a calendar to get the date formatted properly
567
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
568
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
569
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
570
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
571
        Calendar calendar = new GregorianCalendar(pdt);
572
        Date trialTime = new Date();
573
        calendar.setTime(trialTime);
574
        guid.append(calendar.get(Calendar.YEAR));
575
        guid.append(calendar.get(Calendar.DAY_OF_YEAR));
576
        guid.append(calendar.get(Calendar.HOUR_OF_DAY));
577
        guid.append(calendar.get(Calendar.MINUTE));
578
        guid.append(calendar.get(Calendar.SECOND));
579
        guid.append(calendar.get(Calendar.MILLISECOND));
580

    
581
        return guid.toString();
582
    }
583
}
    (1-1/1)