Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2003 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *  Purpose: To test the MetaCatURL class by JUnit
6
 *
7
 *   '$Author: sgarg $'
8
 *     '$Date: 2004-09-02 14:43:59 -0700 (Thu, 02 Sep 2004) $'
9
 * '$Revision: 2265 $'
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 2 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program; if not, write to the Free Software
23
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24
 */
25

    
26
package edu.ucsb.nceas.metacattest.client;
27

    
28
import java.io.File;
29
import java.io.FileReader;
30
import java.io.IOException;
31
import java.io.Reader;
32
import java.io.StringReader;
33
import java.util.Calendar;
34
import java.util.Date;
35
import java.util.GregorianCalendar;
36
import java.util.SimpleTimeZone;
37
import java.util.TimeZone;
38

    
39
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
40
import edu.ucsb.nceas.metacat.client.Metacat;
41
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
42
import edu.ucsb.nceas.metacat.client.MetacatException;
43
import edu.ucsb.nceas.metacat.client.MetacatFactory;
44
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
45
import edu.ucsb.nceas.utilities.IOUtil;
46
import junit.framework.Test;
47
import junit.framework.TestCase;
48
import junit.framework.TestSuite;
49
import java.io.FileInputStream;
50

    
51
/**
52
 * A JUnit test for testing Step class processing
53
 */
54
public class MetacatClientTest extends TestCase
55
{
56
    private String metacatUrl = "@systemidserver@@servlet-path@";
57
    private String wrongMetacatUrl=
58
                    "http://somepalce.somewhere.com/some/servlet/metacat";
59
    private String username = "@mcuser@";
60
    private String password = "@mcpassword@";
61
    private String anotheruser = "@mcanotheruser@";
62
    private String anotherpassword = "@mcanotherpassword@";
63
    private String failpass = "uidfnkj43987yfdn";
64
    private String prefix = "test";
65
    private String newdocid = null;
66
    private String testfile = "test/jones.204.22.xml";
67
    private String onlinetestdatafile = "test/onlineDataFile1";
68
    private String queryFile = "test/query.xml";
69
    private String testdocument = "";
70
    private Metacat m;
71

    
72
    /**
73
     * Constructor to build the test
74
     *
75
     * @param name the name of the test method
76
     */
77
    public MetacatClientTest(String name)
78
    {
79
        super(name);
80
        newdocid = generateDocid();
81
    }
82

    
83
    /**
84
     * Establish a testing framework by initializing appropriate objects
85
     */
86
    public void setUp()
87
    {
88
        try {
89
            FileReader fr = new FileReader(testfile);
90
            testdocument = IOUtil.getAsString(fr, true);
91
        } catch (IOException ioe) {
92
            fail("Can't read test data to run the test: " + testfile);
93
        }
94

    
95
        try {
96
            System.err.println("Test Metacat: " + metacatUrl);
97
            m = MetacatFactory.createMetacatConnection(metacatUrl);
98
        } catch (MetacatInaccessibleException mie) {
99
            System.err.println("Metacat is: " + metacatUrl);
100
            fail("Metacat connection failed." + mie.getMessage());
101
        }
102
    }
103

    
104
    /**
105
     * Release any objects after tests are complete
106
     */
107
    public void tearDown()
108
    {
109
    }
110

    
111
    /**
112
     * Create a suite of tests to be run together
113
     */
114
    public static Test suite()
115
    {
116
      TestSuite suite = new TestSuite();
117
      suite.addTest(new MetacatClientTest("initialize"));
118
      suite.addTest(new MetacatClientTest("invalidLogin"));
119
      suite.addTest(new MetacatClientTest("logoutAndInvalidInsert"));
120
      suite.addTest(new MetacatClientTest("login"));
121
      suite.addTest(new MetacatClientTest("insert"));
122
      suite.addTest(new MetacatClientTest("upload"));
123
      suite.addTest(new MetacatClientTest("upload_stream"));
124
      suite.addTest(new MetacatClientTest("invalidRead"));
125
      suite.addTest(new MetacatClientTest("read"));
126
      suite.addTest(new MetacatClientTest("query"));
127
      suite.addTest(new MetacatClientTest("invalidUpdate"));
128
      suite.addTest(new MetacatClientTest("update"));
129
      suite.addTest(new MetacatClientTest("invalidDelete"));
130
      suite.addTest(new MetacatClientTest("delete"));
131
      suite.addTest(new MetacatClientTest("inaccessibleMetacat"));
132
      suite.addTest(new MetacatClientTest("reuseSession"));
133
      suite.addTest(new MetacatClientTest("reuseInvalidSession"));
134
      return suite;
135
  }
136

    
137
    /**
138
     * Run an initial test that always passes to check that the test
139
     * harness is working.
140
     */
141
    public void initialize()
142
    {
143
        assertTrue(1 == 1);
144
    }
145

    
146
    /**
147
     * Test the login() function with valid credentials
148
     */
149
    public void login()
150
    {
151
        // Try a valid login
152
        try {
153
            String response = m.login(username, password);
154
            System.err.println("Login response: " + response);
155
            assertTrue(response != null);
156
            assertTrue(response.indexOf("<login>") != -1);
157
            String sessionId = m.getSessionId();
158
            System.err.println("Session ID: " + m.getSessionId());
159
            assertTrue(sessionId != null);
160
            assertTrue(response.indexOf(m.getSessionId()) != -1);
161
        } catch (MetacatAuthException mae) {
162
            fail("Authorization failed:\n" + mae.getMessage());
163
        } catch (MetacatInaccessibleException mie) {
164
            fail("Metacat Inaccessible:\n" + mie.getMessage());
165
        }
166
    }
167

    
168
    /**
169
     * Test the login() function with INVALID credentials
170
     */
171
    public void invalidLogin()
172
    {
173
        // Try an invalid login
174
        try {
175
            m.login(username, failpass);
176
            fail("Authorization should have failed.");
177
        } catch (MetacatAuthException mae) {
178
            assertTrue(1 == 1);
179
        } catch (MetacatInaccessibleException mie) {
180
            fail("Metacat Inaccessible:\n" + mie.getMessage());
181
        }
182
    }
183

    
184
    /**
185
     * Test the logout() function. When logout, user will be public, it couldn't
186
     * insert a document.
187
     */
188
    public void logoutAndInvalidInsert()
189
    {
190
       try {
191
            String identifier = newdocid + ".1";
192
            m.login(username, password);
193
            m.logout();
194
            String response = m.insert(identifier,
195
                    new StringReader(testdocument), null);
196
            System.err.println("Response in logout: "+response);
197
            assertTrue(response.indexOf("<success>") == -1);
198
        } catch (MetacatAuthException mae) {
199
            fail("Authorization failed:\n" + mae.getMessage());
200
        } catch (MetacatInaccessibleException mie) {
201
            fail("Metacat Inaccessible:\n" + mie.getMessage());
202
        } catch (InsufficientKarmaException ike) {
203
            fail("Insufficient karma:\n" + ike.getMessage());
204
        } catch (MetacatException me) {
205
            if(me.getMessage().
206
              indexOf("Permission denied for user public inser") == -1){
207
               fail("Metacat Error:\n" + me.getMessage());
208
           }
209
        } catch (Exception e) {
210
            fail("General exception:\n" + e.getMessage());
211
        }
212
    }
213

    
214
    /**
215
     * Test the read() function with a known document
216
     */
217
    public void read()
218
    {
219
        try {
220
            m.login(username, password);
221
            Reader r = m.read(newdocid+".1");
222
            String doc = IOUtil.getAsString(r, true);
223
            doc = doc +"\n";
224
            System.err.println(doc);
225
            assertTrue(doc.equals(testdocument));
226
        } catch (MetacatAuthException mae) {
227
            fail("Authorization failed:\n" + mae.getMessage());
228
        } catch (MetacatInaccessibleException mie) {
229
            fail("Metacat Inaccessible:\n" + mie.getMessage());
230
        } catch (Exception e) {
231
            fail("General exception:\n" + e.getMessage());
232
        }
233
    }
234

    
235
    /**
236
     * A user try to read a document which it doesn't have read permission
237
     */
238
    public void invalidRead()
239
    {
240
        try {
241
            m.login(anotheruser, anotherpassword);
242
            Reader r = m.read(newdocid+".1");
243
            String doc = IOUtil.getAsString(r, true);
244
            assertTrue(doc.indexOf("<error>") != -1);
245
            System.err.println(doc);
246
        } catch (MetacatAuthException mae) {
247
            fail("Authorization failed:\n" + mae.getMessage());
248
        } catch (MetacatInaccessibleException mie) {
249
            fail("Metacat Inaccessible:\n" + mie.getMessage());
250
        } catch (InsufficientKarmaException ike) {
251
            assertTrue(1 == 1);
252
        } catch (MetacatException e) {
253
            fail("Metacat exception:\n" + e.getMessage());
254
        } catch (IOException ioe) {
255
            fail("IO exception:\n" + ioe.getMessage());
256
        }
257
    }
258

    
259
    /**
260
     * Test the query() function with a known document
261
     */
262
    public void query()
263
    {
264
        try {
265
            m.login(username,password);
266
            FileReader fr = new FileReader(queryFile);
267
            Reader r = m.query(fr);
268
            System.err.println("Starting query...");
269
            String result = IOUtil.getAsString(r, true);
270
            System.err.println("Query result:\n" + result);
271
            assertTrue(result.indexOf(newdocid+".1")!=-1);
272
        } catch (MetacatAuthException mae) {
273
            fail("Authorization failed:\n" + mae.getMessage());
274
        } catch (MetacatInaccessibleException mie) {
275
            fail("Metacat Inaccessible:\n" + mie.getMessage());
276
        } catch (Exception e) {
277
            fail("General exception:\n" + e.getMessage());
278
        }
279
    }
280

    
281
    /**
282
     * Test the insert() function with a known document
283
     */
284
    public void insert()
285
    {
286
        try {
287
            String identifier = newdocid + ".1";
288
            m.login(username, password);
289
            String response = m.insert(identifier,
290
                    new StringReader(testdocument), null);
291
            assertTrue(response.indexOf("<success>") != -1);
292
            assertTrue(response.indexOf(identifier) != -1);
293
            System.err.println(response);
294

    
295
        } catch (MetacatAuthException mae) {
296
            fail("Authorization failed:\n" + mae.getMessage());
297
        } catch (MetacatInaccessibleException mie) {
298
            fail("Metacat Inaccessible:\n" + mie.getMessage());
299
        } catch (InsufficientKarmaException ike) {
300
            assertTrue(1 == 1);
301
            fail("Insufficient karma:\n" + ike.getMessage());
302
        } catch (MetacatException me) {
303
            fail("Metacat Error:\n" + me.getMessage());
304
        } catch (Exception e) {
305
            fail("General exception:\n" + e.getMessage());
306
        }
307
    }
308

    
309
    /**
310
     * Test the upload() function with a known document
311
     */
312
    public void upload()
313
    {
314
        try {
315
            newdocid = generateDocid();
316
            String identifier = newdocid + ".1";
317
            m.login(username, password);
318
            String response = m.upload(identifier,
319
                                     new File(onlinetestdatafile));
320
            assertTrue(response.indexOf("<success>") != -1);
321
            assertTrue(response.indexOf(identifier) != -1);
322
            System.err.println(response);
323

    
324
        } catch (MetacatAuthException mae) {
325
            fail("Authorization failed:\n" + mae.getMessage());
326
        } catch (MetacatInaccessibleException mie) {
327
          mie.printStackTrace();
328
            fail("Metacat Inaccessible:\n" + mie.getMessage());
329
        } catch (InsufficientKarmaException ike) {
330
            assertTrue(1 == 1);
331
            fail("Insufficient karma:\n" + ike.getMessage());
332
        } catch (MetacatException me) {
333
            fail("Metacat Error:\n" + me.getMessage());
334
        } catch (Exception e) {
335
            fail("General exception:\n" + e.getMessage());
336
        }
337
    }
338

    
339
    /**
340
     * Test the upload() function by passing an InputStream
341
     */
342
    public void upload_stream()
343
    {
344
        try {
345
            newdocid = generateDocid();
346
            String identifier = newdocid + ".1";
347
            m.login(username, password);
348
            File testFile = new File(onlinetestdatafile);
349
            String response = m.upload(identifier, "onlineDataFile1",
350
                                       new FileInputStream(testFile),
351
                                       (int) testFile.length());
352

    
353
            assertTrue(response.indexOf("<success>") != -1);
354
            assertTrue(response.indexOf(identifier) != -1);
355
            System.err.println(response);
356

    
357
        } catch (MetacatAuthException mae) {
358
            fail("Authorization failed:\n" + mae.getMessage());
359
        } catch (MetacatInaccessibleException mie) {
360
          mie.printStackTrace();
361
            fail("Metacat Inaccessible:\n" + mie.getMessage());
362
        } catch (InsufficientKarmaException ike) {
363
            assertTrue(1 == 1);
364
            fail("Insufficient karma:\n" + ike.getMessage());
365
        } catch (MetacatException me) {
366
            fail("Metacat Error:\n" + me.getMessage());
367
        } catch (Exception e) {
368
            fail("General exception:\n" + e.getMessage());
369
        }
370
    }
371

    
372
    /**
373
     * Test the invalidUpdate() function. A user try to update a document
374
     * which it doesn't have permission
375
     */
376
    public void invalidUpdate()
377
    {
378
        try {
379
            String identifier = newdocid + ".2";
380
            m.login(anotheruser, anotherpassword);
381
            String response = m.update(identifier,
382
                    new StringReader(testdocument), null);
383
            assertTrue(response.indexOf("<success>") == -1);
384

    
385
        } catch (MetacatAuthException mae) {
386
            fail("Authorization failed:\n" + mae.getMessage());
387
        } catch (MetacatInaccessibleException mie) {
388
            fail("Metacat Inaccessible:\n" + mie.getMessage());
389
        } catch (InsufficientKarmaException ike) {
390
            assertTrue(1 == 1);
391
        } catch (MetacatException me) {
392
            fail("Metacat Error:\n" + me.getMessage());
393
        } catch (Exception e) {
394
            fail("General exception:\n" + e.getMessage());
395
        }
396
    }
397

    
398
    /**
399
     * Test the update() function with a known document
400
     */
401
    public void update()
402
    {
403
        try {
404
            String identifier = newdocid + ".2";
405
            m.login(username, password);
406
            String response = m.update(identifier,
407
                    new StringReader(testdocument), null);
408
            assertTrue(response.indexOf("<success>") != -1);
409
            assertTrue(response.indexOf(identifier) != -1);
410
            System.err.println(response);
411

    
412
        } catch (MetacatAuthException mae) {
413
            fail("Authorization failed:\n" + mae.getMessage());
414
        } catch (MetacatInaccessibleException mie) {
415
            fail("Metacat Inaccessible:\n" + mie.getMessage());
416
        } catch (InsufficientKarmaException ike) {
417
            fail("Insufficient karma:\n" + ike.getMessage());
418
        } catch (MetacatException me) {
419
            fail("Metacat Error:\n" + me.getMessage());
420
        } catch (Exception e) {
421
            fail("General exception:\n" + e.getMessage());
422
        }
423
    }
424

    
425
    /**
426
     * A user try delete a document which it doesn't have permission
427
     */
428
    public void invalidDelete()
429
    {
430
        try {
431
            String identifier = newdocid + ".2";
432
            m.login(anotheruser, anotherpassword);
433
            String response = m.delete(identifier);
434
            assertTrue(response.indexOf("<success>") == -1);
435
            System.err.println(response);
436

    
437
        } catch (MetacatAuthException mae) {
438
            fail("Authorization failed:\n" + mae.getMessage());
439
        } catch (MetacatInaccessibleException mie) {
440
            fail("Metacat Inaccessible:\n" + mie.getMessage());
441
        } catch (InsufficientKarmaException ike) {
442
            assertTrue(1 == 1);
443
        } catch (MetacatException me) {
444
            assertTrue(1 == 1);
445
        } catch (Exception e) {
446
            fail("General exception:\n" + e.getMessage());
447
        }
448
    }
449

    
450
    /**
451
     * Test the delete() function with a known document
452
     */
453
    public void delete()
454
    {
455
        try {
456
            String identifier = newdocid + ".2";
457
            m.login(username, password);
458
            String response = m.delete(identifier);
459
            assertTrue(response.indexOf("<success>") != -1);
460
            System.err.println(response);
461

    
462
        } catch (MetacatAuthException mae) {
463
            fail("Authorization failed:\n" + mae.getMessage());
464
        } catch (MetacatInaccessibleException mie) {
465
            fail("Metacat Inaccessible:\n" + mie.getMessage());
466
        } catch (InsufficientKarmaException ike) {
467
            fail("Insufficient karma:\n" + ike.getMessage());
468
        } catch (MetacatException me) {
469
            fail("Metacat Error:\n" + me.getMessage());
470
        } catch (Exception e) {
471
            fail("General exception:\n" + e.getMessage());
472
        }
473
    }
474

    
475
    /**
476
     * Test the to connect a wrong metacat url. Create a new metacat with a
477
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
478
     * exception, this is right.
479
     */
480
    public void inaccessibleMetacat()
481
    {
482
        Metacat mWrong = null;
483
        try {
484
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
485
        } catch (MetacatInaccessibleException mie) {
486
            fail("Metacat Inaccessible:\n" + mie.getMessage());
487
        }
488

    
489
        try {
490
            mWrong.login(username, password);
491
        } catch (MetacatInaccessibleException mie) {
492
            assertTrue(1 == 1);
493
        } catch (MetacatAuthException mae) {
494
            fail("Authorization failed:\n" + mae.getMessage());
495
        }
496
    }
497

    
498
    /**
499
     * Try to perform an action that requires a session to be valid without
500
     * having logged in first by setting the sessionId from a previous
501
     * session.  Then insert a document.
502
     */
503
    public void reuseSession()
504
    {
505
        String oldSessionId = "";
506
        try {
507
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
508
            String response = mtemp.login(username, password);
509
            oldSessionId = mtemp.getSessionId();
510
            System.err.println("SessionId (mtemp): " + oldSessionId);
511
        } catch (MetacatAuthException mae) {
512
            fail("Authorization failed:\n" + mae.getMessage());
513
        } catch (MetacatInaccessibleException mie) {
514
            System.err.println("Metacat is: " + metacatUrl);
515
            fail("Metacat connection failed." + mie.getMessage());
516
        }
517

    
518
        try {
519
            String identifier = generateDocid() + ".1";
520
            Metacat m2 = null;
521
            try {
522
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
523
            } catch (MetacatInaccessibleException mie) {
524
                System.err.println("Metacat is: " + metacatUrl);
525
                fail("Metacat connection failed." + mie.getMessage());
526
            }
527
            System.err.println("SessionId (m2): " + m2.getSessionId());
528
            m2.setSessionId(oldSessionId);
529
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
530
            String response = m2.insert(identifier,
531
                    new StringReader(testdocument), null);
532
            System.err.println("Reuse Insert response: " + response);
533
            assertTrue(response.indexOf("<success>") != -1);
534
        } catch (MetacatInaccessibleException mie) {
535
            fail("Metacat Inaccessible:\n" + mie.getMessage());
536
        } catch (InsufficientKarmaException ike) {
537
            fail("Insufficient karma:\n" + ike.getMessage());
538
        } catch (MetacatException me) {
539
            fail("Metacat Error:\n" + me.getMessage());
540
        } catch (Exception e) {
541
            fail("General exception:\n" + e.getMessage());
542
        }
543
    }
544

    
545
    /**
546
     * Try to perform an action that requires a session to be valid without
547
     * having logged in first, but use an invalid session identifier.
548
     * Then insert a document, which should fail.
549
     */
550
    public void reuseInvalidSession()
551
    {
552
        System.err.println("Starting resuseInvalidSession test...");
553
        String oldSessionId = "foobar";
554
        try {
555
            String identifier = generateDocid() + ".1";
556
            Metacat m3 = null;
557
            try {
558
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
559
            } catch (MetacatInaccessibleException mie) {
560
                System.err.println("Metacat is: " + metacatUrl);
561
                fail("Metacat connection failed." + mie.getMessage());
562
            }
563
            System.err.println("SessionId (m3): " + m3.getSessionId());
564
            m3.setSessionId(oldSessionId);
565
            System.err.println("SessionId (m3 after set): " + m3.getSessionId());
566
            System.err.println("Performing resuseInvalidSession insert: " +
567
                    identifier);
568
            String response = m3.insert(identifier,
569
                    new StringReader(testdocument), null);
570
            System.err.println("ReuseInvalid Insert response: " + response);
571
            assertTrue(response.indexOf("<success>") == -1);
572
        } catch (MetacatInaccessibleException mie) {
573
            fail("Metacat Inaccessible:\n" + mie.getMessage());
574
        } catch (InsufficientKarmaException ike) {
575
            fail("Insufficient karma:\n" + ike.getMessage());
576
        } catch (MetacatException me) {
577
            if(me.getMessage().
578
               indexOf("Permission denied for user public inser") == -1){
579
                fail("Metacat Error:\n" + me.getMessage());
580
            }
581
        } catch (Exception e) {
582
            fail("General exception:\n" + e.getMessage());
583
        }
584
    }
585
    /**
586
     * Create a hopefully unique docid for testing insert and update. Does
587
     * not include the 'revision' part of the id.
588
     *
589
     * @return a String docid based on the current date and time
590
     */
591
    private String generateDocid()
592
    {
593
        StringBuffer docid = new StringBuffer(prefix);
594
        docid.append(".");
595

    
596
        // Create a calendar to get the date formatted properly
597
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
598
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
599
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);
600
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
601
        Calendar calendar = new GregorianCalendar(pdt);
602
        Date trialTime = new Date();
603
        calendar.setTime(trialTime);
604
        docid.append(calendar.get(Calendar.YEAR));
605
        docid.append(calendar.get(Calendar.DAY_OF_YEAR));
606
        docid.append(calendar.get(Calendar.HOUR_OF_DAY));
607
        docid.append(calendar.get(Calendar.MINUTE));
608
        docid.append(calendar.get(Calendar.SECOND));
609

    
610
        return docid.toString();
611
    }
612
}
    (1-1/1)