Project

General

Profile

1 5211 jones
/**
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 5284 jones
import java.io.StringReader;
28 5286 jones
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 5211 jones
import java.util.Vector;
34
35
import junit.framework.Test;
36
import junit.framework.TestSuite;
37
import edu.ucsb.nceas.MCTestCase;
38 5284 jones
import edu.ucsb.nceas.metacat.IdentifierManager;
39 5211 jones
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
40 5284 jones
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
41 5211 jones
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 6095 jones
 * A JUnit test for testing Step class processing.
52
 *
53
 * This test is deprecated because the associated RestClient will be removed.
54 5211 jones
 */
55 6095 jones
@Deprecated
56 5211 jones
public class MetacatRestClientTest extends MCTestCase{
57
	protected static String contextUrl;
58
	static {
59
		try {
60
		    contextUrl = PropertyService.getProperty("test.contextUrl");
61
			username = PropertyService.getProperty("test.mcUser");
62
			password = PropertyService.getProperty("test.mcPassword");
63
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
64
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
65
		} catch (PropertyNotFoundException pnfe) {
66
			System.err.println("Could not get property in static block: "
67
					+ pnfe.getMessage());
68
		}
69
	}
70
71
    private String failpass = "sdfsdfsdfsd";
72
    private MetacatRest m;
73 5284 jones
    private static final String DOC_TITLE = "Test MetacatRest service";
74 5211 jones
75
    /**
76
     * Constructor to build the test
77
     *
78
     * @param name the name of the test method
79
     */
80
    public MetacatRestClientTest(String name)
81
    {
82
        super(name);
83
    }
84
85
    /**
86
     * Establish a testing framework by initializing appropriate objects
87
     */
88
    public void setUp()
89
    {
90 5337 berkley
        System.out.println("contextUrl: " + contextUrl);
91 5211 jones
        m = new MetacatRestClient(contextUrl);
92
    }
93
94
    /**
95
     * Release any objects after tests are complete
96
     */
97
    public void tearDown()
98
    {
99
    }
100
101
    /**
102
     * Create a suite of tests to be run together
103
     */
104
    public static Test suite()
105
    {
106
      TestSuite suite = new TestSuite();
107
      suite.addTest(new MetacatRestClientTest("initialize"));
108 6095 jones
109
      // Commented out tests because these servlets are no longer configured in metacat
110
      // so they all need to be removed along with MetacatRestClient
111
//      suite.addTest(new MetacatRestClientTest("invalidLogin"));
112
//      suite.addTest(new MetacatRestClientTest("login"));
113
//      suite.addTest(new MetacatRestClientTest("logout"));
114
//      suite.addTest(new MetacatRestClientTest("get"));
115
//      suite.addTest(new MetacatRestClientTest("invalidGet"));
116
//      suite.addTest(new MetacatRestClientTest("getPrivate"));
117
//      suite.addTest(new MetacatRestClientTest("authenticatedGet"));
118
//      suite.addTest(new MetacatRestClientTest("query"));
119
//      suite.addTest(new MetacatRestClientTest("authenticatedQuery"));
120
//      suite.addTest(new MetacatRestClientTest("crud"));
121
//      suite.addTest(new MetacatRestClientTest("delete"));
122
//      suite.addTest(new MetacatRestClientTest("getNextObject"));
123
//      suite.addTest(new MetacatRestClientTest("getNextRevision"));
124
//      suite.addTest(new MetacatRestClientTest("getAllDocids"));
125
//      suite.addTest(new MetacatRestClientTest("isRegistered"));
126
//      suite.addTest(new MetacatRestClientTest("addLSID"));
127 5211 jones
      return suite;
128
  }
129
130
131
    /**
132
     * Run an initial test that always passes to check that the test
133
     * harness is working.
134
     */
135 5284 jones
    public void initialize()
136
    {
137 5211 jones
        assertTrue(1 == 1);
138
    }
139
140
    /**
141
     * Test the login() function with valid credentials
142
     */
143
    public void login()
144
    {
145
        debug("\nStarting login test...");
146
        debug("-------------------------------------------------------");
147
        // Try a valid login
148
        try {
149
            String response = m.login(username, password);
150
            debug("login(): response=" + response);
151
            assertTrue(response != null);
152
            assertTrue(response.indexOf("<login>") != -1);
153
            String sessionId = m.getSessionId();
154
            debug("login(): Session ID=" + m.getSessionId());
155
            assertTrue(sessionId != null);
156
            assertTrue(response.indexOf(m.getSessionId()) != -1);
157
        } catch (MetacatAuthException mae) {
158
            fail("Authorization failed:\n" + mae.getMessage());
159
        } catch (MetacatInaccessibleException mie) {
160
            fail("Metacat Inaccessible:\n" + mie.getMessage());
161
        }
162
    }
163
164
    /**
165
     * Test the login() function with INVALID credentials
166
     */
167
    public void invalidLogin()
168
    {
169
        debug("\nStarting invalidLogin test...");
170
        debug("-------------------------------------------------------");
171
        // Try an invalid login
172
        String response = "";
173
        try {
174
        	response = m.login(username, failpass);
175
            fail("Authorization should have failed.");
176
        } catch (MetacatAuthException mae) {
177
        	debug("invalid login(): response=" + mae.getMessage());
178 5284 jones
            assertNotNull(mae);
179 5211 jones
        } catch (MetacatInaccessibleException mie) {
180
            fail("Metacat Inaccessible:\n" + mie.getMessage());
181
        }
182
    }
183
184
    /**
185
     * Test the logout() function.
186
     */
187
    public void logout()
188
    {
189
       debug("\nStarting logout test...");
190
       debug("-------------------------------------------------------");
191
       try {
192
            m.login(username, password);
193
            String response = m.logout();
194
            debug("logout(): Response ="+response);
195
            assertTrue(response.indexOf("<success>") == -1);
196
        } catch (MetacatAuthException mae) {
197
            fail("Authorization failed:\n" + mae.getMessage());
198
        } catch (MetacatInaccessibleException mie) {
199
            fail("Metacat Inaccessible:\n" + mie.getMessage());
200
        } catch (MetacatException me) {
201
            if(me.getMessage().
202
              indexOf("Permission denied for user public inser") == -1){
203
               fail("Metacat Error:\n" + me.getMessage());
204
           }
205
        } catch (Exception e) {
206
            fail("General exception:\n" + e.getMessage());
207
        }
208
    }
209
210
211
    /**
212
     * Test the get() function with a public document
213
     */
214
    public void get()
215
    {
216
        debug("\nStarting get test...");
217 5284 jones
        debug("-------------------------------------------------------");
218 5211 jones
        try {
219 5286 jones
            String guid = insertTestDocument();
220 5284 jones
            Reader r =  m.getObject(guid, null);
221 5211 jones
            String doc = IOUtil.getAsString(r, true);
222
            doc = doc +"\n";
223
            debug("document:\n"+doc);
224 5284 jones
            assertTrue(doc.indexOf(DOC_TITLE) != -1);
225 5211 jones
        } catch (MetacatInaccessibleException mie) {
226 5284 jones
            fail("Metacat Inaccessible:\n" + mie.getMessage());
227 5211 jones
        } catch (Exception e) {
228 5284 jones
            fail("General exception:\n" + e.getMessage());
229 5211 jones
        }
230
    }
231
232
    /**
233
     * Test the get() function with a private document
234
     */
235
    public void getPrivate()
236
    {
237 5284 jones
        assertTrue("Not implemented yet.", 1==1);
238
        /*
239 5211 jones
        debug("\nStarting getprivate  test...");
240
        debug("-------------------------------------------------------");
241
        try {
242
            Reader r =  m.getObject(authorized_doc_id, null);
243
            String doc = IOUtil.getAsString(r, true);
244
            doc = doc +"\n";
245
            debug("document:\n"+doc);
246
        } catch (MetacatInaccessibleException mie) {
247 5284 jones
            fail("Metacat Inaccessible:\n" + mie.getMessage());
248 5211 jones
        } catch (Exception e) {
249 5284 jones
            fail("General exception:\n" + e.getMessage());
250 5211 jones
        }
251 5284 jones
        */
252 5211 jones
    }
253
254
    /**
255
     * Test the authenticatedGet() function with a private document without for a valid session
256
     */
257
    public void authenticatedGet()
258
    {
259 5284 jones
        assertTrue("Not implemented yet.", 1==1);
260
        /*
261 5211 jones
        debug("\nStarting authorizedGet test...");
262
        debug("-------------------------------------------------------");
263
        try {
264
        	m.login(username,password);
265
            Reader r =  m.authenticatedGetObject(authorized_doc_id, null);
266
            String doc = IOUtil.getAsString(r, true);
267
            doc = doc +"\n";
268
            debug("document:\n"+doc);
269
        } catch (MetacatInaccessibleException mie) {
270
            debug("Metacat Inaccessible:\n" + mie.getMessage());
271
        } catch (Exception e) {
272
            debug("General exception:\n" + e.getMessage());
273
        }
274 5284 jones
        */
275 5211 jones
    }
276
277
    /**
278 5291 jones
     * Test the get() function with a non existing document
279 5211 jones
     */
280
    public void invalidGet()
281
    {
282
        debug("\nStarting invalid get test ...");
283
        debug("-------------------------------------------------------");
284
        try {
285 5284 jones
            String unregDocid = generateDocumentId() + ".1";
286
            Reader r =  m.getObject(unregDocid, null);
287 5211 jones
            String doc = IOUtil.getAsString(r, true);
288
            doc = doc +"\n";
289
            debug("document:\n"+doc);
290 5284 jones
            assertTrue(doc.indexOf("<error>") != -1);
291 5211 jones
        } catch (MetacatInaccessibleException mie) {
292
            debug("Metacat Inaccessible:\n" + mie.getMessage());
293
        } catch (DocumentNotFoundException doe) {
294
        	  debug("Document not found:\n" + doe.getMessage());
295
        } catch (Exception e) {
296
        	e.printStackTrace();
297
            debug("General exception:\n" + e.getMessage());
298
        }
299
    }
300
301
    /**
302
     * Test the query() function with a public session
303
     */
304 5284 jones
    public void query()
305
    {
306
        assertTrue("Not implemented yet.", 1==1);
307
        /*
308 5211 jones
    	debug("\nStarting query test ...");
309
        debug("-------------------------------------------------------");
310
    	try {
311
    	 FileReader fr = new FileReader(ecogridQueryFile);
312
    	 Reader r = m.query(fr);
313
         String doc = IOUtil.getAsString(r, true);
314
         doc = doc +"\n";
315
         debug("document:\n"+doc);
316
317
        } catch (MetacatInaccessibleException mie) {
318
            fail("Metacat Inaccessible:\n" + mie.getMessage());
319
        } catch (Exception e) {
320
        	e.printStackTrace();
321
            fail("General exception:\n" + e.getMessage());
322
        }
323 5284 jones
        */
324 5211 jones
    }
325
326
327
328
    /**
329
     * Test the authenticatedQuery() function
330
     */
331 5284 jones
    public void authenticatedQuery()
332
    {
333
        assertTrue("Not implemented yet.", 1==1);
334
        /*
335 5211 jones
    	debug("\nStarting authenticatedQuery test ...");
336
        debug("-------------------------------------------------------");
337
    	try {
338
    	 FileReader fr = new FileReader(ecogridQueryFile);
339
    	 m.login(username,password);
340
    	 Reader r = m.authenticatedQuery(fr);
341
         String doc = IOUtil.getAsString(r, true);
342
         doc = doc +"\n";
343
         debug("document:\n"+doc);
344
345
        } catch (MetacatAuthException mae) {
346
            fail("Authorization failed:\n" + mae.getMessage());
347
        } catch (MetacatInaccessibleException mie) {
348
            fail("Metacat Inaccessible:\n" + mie.getMessage());
349
        } catch (Exception e) {
350
        	e.printStackTrace();
351
            fail("General exception:\n" + e.getMessage());
352
        }
353 5284 jones
        */
354 5211 jones
    }
355
356
    /**
357
     * Test the insert,update and delete function
358
     */
359 5284 jones
    public void crud()
360
    {
361 5287 jones
    	debug("\nStarting insert and update document test ...");
362 5211 jones
        debug("-------------------------------------------------------");
363
    	try {
364 5284 jones
    	    String accessBlock = getAccessBlock("public", true, true,
365
                    false, false, false);
366
            String emldoc = getTestEmlDoc("Test MetacatRest service", EML2_1_0, null,
367
                    null, "http://fake.example.com/somedata", null,
368
                    accessBlock, null, null,
369
                    null, null);
370
            String docid = generateDocumentId();
371 5286 jones
            debug("Generated id: " + docid);
372 5284 jones
    		StringReader sr = new StringReader(emldoc);
373 5211 jones
    		m.login(username,password);
374
375
    		debug("\nFirst insert the document...");
376 5291 jones
    		String response = m.create(docid + ".1",sr);
377 5284 jones
    		sr.close();
378 5211 jones
    		debug("response:\n"+response);
379 5284 jones
            assertTrue(response.indexOf("success") != -1);
380
381 5286 jones
            Thread.sleep(5000);
382
383 5284 jones
    		sr = new StringReader(emldoc);
384 5211 jones
    		debug("\nNow update the document...");
385 5291 jones
    		response = m.update(docid + ".2",sr);
386 5284 jones
    		debug("response:\n"+response);
387
            assertTrue(response.indexOf("success") != -1);
388
    		sr.close();
389 5211 jones
390
    	} catch (MetacatAuthException mae) {
391 5284 jones
    		fail("Authorization failed:\n" + mae.getMessage());
392 5211 jones
    	} catch (MetacatInaccessibleException mie) {
393 5284 jones
    		fail("Metacat Inaccessible:\n" + mie.getMessage());
394 5211 jones
    	} catch (Exception e) {
395
    		fail("General exception:\n" + e.getMessage());
396
    	}
397
    }
398
399 5287 jones
    /**
400
     * Test the delete function
401
     */
402
    public void delete()
403
    {
404
        debug("\nStarting delete document test ...");
405
        debug("-------------------------------------------------------");
406
        try {
407
            String guid = insertTestDocument();
408
            try {
409
                Thread.sleep(5000);
410
            } catch (InterruptedException e) {
411
                debug("Thread.sleep() failed to execute.");
412
            }
413
414
            debug("\nDelete the document...");
415
            String response = m.deleteObject(guid);
416
            debug("response:\n"+response);
417
            assertTrue(response.indexOf("success") != -1);
418
419
        } catch (MetacatInaccessibleException mie) {
420
            fail("Metacat Inaccessible:\n" + mie.getMessage());
421
        } catch (InsufficientKarmaException e) {
422
            fail("not Authorized:\n" + e.getMessage());
423
        } catch (MetacatException e) {
424
            fail("Metacat error:\n" + e.getMessage());
425
        }
426
    }
427 5211 jones
428
    /**
429
     * Get the most recent document id for a given scope and be sure
430
     * that it matches the one we last inserted. Assumes this test is run
431
     * immediately following a successful insert() test.
432
     */
433 5284 jones
    public void getNextObject()
434
    {
435 5211 jones
        debug("\nStarting getNextObject test...");
436
        debug("-------------------------------------------------------");
437
        try {
438
439
            String lastId = m.getNextObject(prefix);
440
            debug("getNextObject(): Last Id=" + lastId);
441
442
        } catch (MetacatException me) {
443
            fail("Metacat Error:\n" + me.getMessage());
444
        } catch (Exception e) {
445
            fail("General exception:\n" + e.getMessage());
446
        }
447
    }
448
449
    /**
450 5284 jones
     * Get the next revision for a given id. Assumes this test is run
451 5211 jones
     * immediately following a successful insert() test.
452
     */
453 5284 jones
    public void getNextRevision()
454
    {
455 5211 jones
        debug("\nStarting getNextRevision test...");
456
        debug("-------------------------------------------------------");
457
        try {
458 5284 jones
            IdentifierManager im = IdentifierManager.getInstance();
459
            String docid = insertTestDocument();
460
            int rev_id = m.getNextRevision(docid);
461 5211 jones
            debug("NextRevision number is " + rev_id);
462
463
        } catch (MetacatException me) {
464
            fail("Metacat Error:\n" + me.getMessage());
465
        } catch (Exception e) {
466
            fail("General exception:\n" + e.getMessage());
467
        }
468
    }
469
470
471
    /**
472
     * Test getAllDocids function
473
     */
474 5284 jones
    public void getAllDocids()
475
    {
476 5211 jones
        debug("\nStarting getAllDocids test...");
477
        debug("-------------------------------------------------------");
478
        try {
479
480
            Vector<String> vector = m.getAllDocids(prefix);
481
            StringBuffer b = new StringBuffer();
482
            for (String doc_id:vector)
483
            	b.append(doc_id+"\n");
484
            debug("getAllDocids():\n " + b.toString());
485
486
        } catch (MetacatException me) {
487
            fail("Metacat Error:\n" + me.getMessage());
488
        } catch (Exception e) {
489
            fail("General exception:\n" + e.getMessage());
490
        }
491
    }
492
493 5284 jones
    /**
494 5211 jones
     * Test isRegistered function
495
     */
496 5284 jones
    public void isRegistered()
497
    {
498 5211 jones
        debug("\nStarting isRegistered test...");
499
        debug("-------------------------------------------------------");
500
        try {
501 5284 jones
            IdentifierManager im = IdentifierManager.getInstance();
502
            String docid = insertTestDocument();
503
            boolean registered = m.isRegistered(docid);
504
            debug("isRegistered(): " + docid + ".1" +" is "+(registered?"":"not ")+"registered");
505
            assertTrue(registered);
506
            String unregDocid = generateDocumentId() + ".1";
507
            registered = m.isRegistered(unregDocid);
508
            debug("isRegistered(): " + unregDocid+" is "+(registered?"":"not ")+"registered");
509
            assertFalse(registered);
510 5211 jones
        } catch (MetacatException me) {
511
            fail("Metacat Error:\n" + me.getMessage());
512
        } catch (Exception e) {
513
            fail("General exception:\n" + e.getMessage());
514
        }
515
    }
516
517 5284 jones
    /**
518 5211 jones
     * Test addLSID function
519
     */
520 5284 jones
    public void addLSID()
521
    {
522 5211 jones
    	  debug("\nStarting addLSID test...");
523
    	  debug("-------------------------------------------------------");
524
          try {
525 5284 jones
              String unregDocid = generateDocumentId() + ".1";
526
        	  String response =  m.addLSID(unregDocid);
527 5211 jones
        	  debug("response:\n"+response);
528
          } catch (MetacatException me) {
529
              fail("Metacat Error:\n" + me.getMessage());
530
          } catch (Exception e) {
531
              fail("General exception:\n" + e.getMessage());
532
          }
533
    }
534 5284 jones
535 5286 jones
    /** Insert a test document, returning the identifier that was used. */
536 5284 jones
    private String insertTestDocument()
537 5211 jones
    {
538 5284 jones
        String accessBlock = getAccessBlock("public", true, true,
539
                false, false, false);
540
        String emldoc = getTestEmlDoc(DOC_TITLE, EML2_1_0, null,
541
                null, "http://fake.example.com/somedata", null,
542
                accessBlock, null, null,
543
                null, null);
544 5286 jones
        //String docid = generateDocumentId() + ".1";
545
        String guid = "testid:" + generateTimeString();
546 5284 jones
        StringReader sr = new StringReader(emldoc);
547
        String response;
548
        try {
549
            m.login(username,password);
550 5291 jones
            response = m.create(guid, sr);
551 5284 jones
            debug("response:\n"+response);
552
            assertTrue(response.indexOf("success") != -1);
553
        } catch (InsufficientKarmaException e) {
554
            fail(e.getMessage());
555
        } catch (MetacatException e) {
556
            fail(e.getMessage());
557
        } catch (IOException e) {
558
            fail(e.getMessage());
559
        } catch (MetacatInaccessibleException e) {
560
            fail(e.getMessage());
561
        } catch (MetacatAuthException e) {
562
            fail(e.getMessage());
563
        }
564 5286 jones
        return guid;
565 5211 jones
    }
566 5286 jones
567
    /** Generate a timestamp for use in IDs. */
568
    private String generateTimeString()
569
    {
570
        StringBuffer guid = new StringBuffer();
571
572
        // Create a calendar to get the date formatted properly
573
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
574
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
575
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
576
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
577
        Calendar calendar = new GregorianCalendar(pdt);
578
        Date trialTime = new Date();
579
        calendar.setTime(trialTime);
580
        guid.append(calendar.get(Calendar.YEAR));
581
        guid.append(calendar.get(Calendar.DAY_OF_YEAR));
582
        guid.append(calendar.get(Calendar.HOUR_OF_DAY));
583
        guid.append(calendar.get(Calendar.MINUTE));
584
        guid.append(calendar.get(Calendar.SECOND));
585
        guid.append(calendar.get(Calendar.MILLISECOND));
586
587
        return guid.toString();
588
    }
589 5211 jones
}