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("delete"));
115
      suite.addTest(new MetacatRestClientTest("getNextObject"));
116
      suite.addTest(new MetacatRestClientTest("getNextRevision"));
117
      suite.addTest(new MetacatRestClientTest("getAllDocids"));
118
      suite.addTest(new MetacatRestClientTest("isRegistered"));
119
      suite.addTest(new MetacatRestClientTest("addLSID"));
120
      return suite;
121
  }
122
    
123
    
124
    /**
125
     * Run an initial test that always passes to check that the test
126
     * harness is working.
127
     */
128
    public void initialize() 
129
    {
130
        assertTrue(1 == 1);
131
    }
132
    
133
    /**
134
     * Test the login() function with valid credentials
135
     */
136
    public void login()
137
    {
138
        debug("\nStarting login test...");
139
        debug("-------------------------------------------------------");
140
        // Try a valid login
141
        try {
142
            String response = m.login(username, password);
143
            debug("login(): response=" + response);
144
            assertTrue(response != null);
145
            assertTrue(response.indexOf("<login>") != -1);
146
            String sessionId = m.getSessionId();
147
            debug("login(): Session ID=" + m.getSessionId());
148
            assertTrue(sessionId != null);
149
            assertTrue(response.indexOf(m.getSessionId()) != -1);
150
        } catch (MetacatAuthException mae) {
151
            fail("Authorization failed:\n" + mae.getMessage());
152
        } catch (MetacatInaccessibleException mie) {
153
            fail("Metacat Inaccessible:\n" + mie.getMessage());
154
        }
155
    }
156
    
157
    /**
158
     * Test the login() function with INVALID credentials
159
     */
160
    public void invalidLogin()
161
    {
162
        debug("\nStarting invalidLogin test...");
163
        debug("-------------------------------------------------------");
164
        // Try an invalid login
165
        String response = "";
166
        try {
167
        	response = m.login(username, failpass);        	
168
            fail("Authorization should have failed.");
169
        } catch (MetacatAuthException mae) {
170
        	debug("invalid login(): response=" + mae.getMessage());
171
            assertNotNull(mae);
172
        } catch (MetacatInaccessibleException mie) {
173
            fail("Metacat Inaccessible:\n" + mie.getMessage());
174
        } 
175
    }
176
    
177
    /**
178
     * Test the logout() function. 
179
     */
180
    public void logout()
181
    {
182
       debug("\nStarting logout test...");
183
       debug("-------------------------------------------------------");
184
       try {
185
            m.login(username, password);
186
            String response = m.logout();
187
            debug("logout(): Response ="+response);
188
            assertTrue(response.indexOf("<success>") == -1);
189
        } catch (MetacatAuthException mae) {
190
            fail("Authorization failed:\n" + mae.getMessage());
191
        } catch (MetacatInaccessibleException mie) {
192
            fail("Metacat Inaccessible:\n" + mie.getMessage());
193
        } catch (MetacatException me) {
194
            if(me.getMessage().
195
              indexOf("Permission denied for user public inser") == -1){
196
               fail("Metacat Error:\n" + me.getMessage());
197
           }
198
        } catch (Exception e) {
199
            fail("General exception:\n" + e.getMessage());
200
        }
201
    }
202
    
203
    
204
    /**
205
     * Test the get() function with a public document
206
     */
207
    public void get()
208
    {
209
        debug("\nStarting get test...");
210
        debug("-------------------------------------------------------"); 
211
        try {
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 and update 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
    	} catch (MetacatAuthException mae) {
384
    		fail("Authorization failed:\n" + mae.getMessage());
385
    	} catch (MetacatInaccessibleException mie) {
386
    		fail("Metacat Inaccessible:\n" + mie.getMessage());
387
    	} catch (Exception e) {
388
    		fail("General exception:\n" + e.getMessage());
389
    	}
390
    }
391

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

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

    
432
            String lastId = m.getNextObject(prefix);
433
            debug("getNextObject(): Last Id=" + lastId);
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
     * Get the next revision for a given id. Assumes this test is run
444
     * immediately following a successful insert() test.
445
     */
446
    public void getNextRevision()
447
    {
448
        debug("\nStarting getNextRevision test...");
449
        debug("-------------------------------------------------------");
450
        try {
451
            IdentifierManager im = IdentifierManager.getInstance();
452
            String docid = insertTestDocument();
453
            int rev_id = m.getNextRevision(docid);
454
            debug("NextRevision number is " + rev_id);
455

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

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

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

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

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