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
        m = new MetacatRestClient(contextUrl);
88
    }
89
    
90
    /**
91
     * Release any objects after tests are complete
92
     */
93
    public void tearDown()
94
    {
95
    }
96

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

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

    
376
    		sr = new StringReader(emldoc);
377
    		debug("\nNow update the document...");
378
    		response = m.putObject(docid + ".2",sr,false);    	 
379
    		debug("response:\n"+response);
380
            assertTrue(response.indexOf("success") != -1);
381
    		sr.close();
382
    		
383
    		Thread.sleep(5000);
384
    		
385
    		debug("\nFinally delete the document...");
386
    		response = m.deleteObject(docid + ".2");  
387
    		debug("response:\n"+response);
388
            assertTrue(response.indexOf("success") != -1);
389

    
390
    	} catch (MetacatAuthException mae) {
391
    		fail("Authorization failed:\n" + mae.getMessage());
392
    	} catch (MetacatInaccessibleException mie) {
393
    		fail("Metacat Inaccessible:\n" + mie.getMessage());
394
    	} catch (Exception e) {
395
    		fail("General exception:\n" + e.getMessage());
396
    	}
397
    }
398

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

    
411
            String lastId = m.getNextObject(prefix);
412
            debug("getNextObject(): Last Id=" + lastId);
413

    
414
        } catch (MetacatException me) {
415
            fail("Metacat Error:\n" + me.getMessage());
416
        } catch (Exception e) {
417
            fail("General exception:\n" + e.getMessage());
418
        }
419
    }
420

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

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

    
452
            Vector<String> vector = m.getAllDocids(prefix);
453
            StringBuffer b = new StringBuffer();
454
            for (String doc_id:vector)
455
            	b.append(doc_id+"\n");
456
            debug("getAllDocids():\n " + b.toString());
457

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

    
544
        // Create a calendar to get the date formatted properly
545
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
546
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
547
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
548
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
549
        Calendar calendar = new GregorianCalendar(pdt);
550
        Date trialTime = new Date();
551
        calendar.setTime(trialTime);
552
        guid.append(calendar.get(Calendar.YEAR));
553
        guid.append(calendar.get(Calendar.DAY_OF_YEAR));
554
        guid.append(calendar.get(Calendar.HOUR_OF_DAY));
555
        guid.append(calendar.get(Calendar.MINUTE));
556
        guid.append(calendar.get(Calendar.SECOND));
557
        guid.append(calendar.get(Calendar.MILLISECOND));
558

    
559
        return guid.toString();
560
    }
561
}
    (1-1/1)