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: tao $'
8
 *     '$Date: 2011-11-29 16:21:51 -0800 (Tue, 29 Nov 2011) $'
9
 * '$Revision: 6716 $'
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.FileWriter;
31
import java.io.InputStream;
32
import java.io.InputStreamReader;
33
import java.io.IOException;
34
import java.io.Reader;
35
import java.io.StringReader;
36
import java.io.StringWriter;
37

    
38
import edu.ucsb.nceas.MCTestCase;
39
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
40
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
41
import edu.ucsb.nceas.metacat.client.Metacat;
42
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
43
import edu.ucsb.nceas.metacat.client.MetacatException;
44
import edu.ucsb.nceas.metacat.client.MetacatFactory;
45
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
46
import edu.ucsb.nceas.metacat.properties.PropertyService;
47
import edu.ucsb.nceas.utilities.IOUtil;
48
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
49
import junit.framework.Test;
50
import junit.framework.TestSuite;
51
import java.io.FileInputStream;
52

    
53
import org.apache.commons.io.IOUtils;
54

    
55

    
56
/**
57
 * A JUnit test for testing Step class processing
58
 */
59
public class MetacatClientTest extends MCTestCase
60
{
61

    
62
    private String wrongMetacatUrl=
63
    	"http://somepalce.somewhere.com/some/servlet/metacat";
64
  
65
    private static String metacatUrl;
66
    private static String username;
67
	private static String password;
68
	private static String anotheruser;
69
	private static String anotherpassword;
70
	static {
71
		try {
72
		    metacatUrl = PropertyService.getProperty("test.metacatUrl");
73
			username = PropertyService.getProperty("test.mcUser");
74
			password = PropertyService.getProperty("test.mcPassword");
75
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
76
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
77
		} catch (PropertyNotFoundException pnfe) {
78
			System.err.println("Could not get property in static block: " 
79
					+ pnfe.getMessage());
80
		}
81
	}
82
    private String failpass = "uidfnkj43987yfdn";
83
    private String newdocid = null;
84
    private String testfile = "test/jones.204.22.xml";
85
    private String testEMLWithAccess = "test/tao.14563.1.xml";
86
    private String onlinetestdatafile = "test/onlineDataFile1";
87
    private String queryFile = "test/query.xml";
88
    private String testdocument = "";
89
    private Metacat m;
90
    private String spatialTestFile = "test/spatialEml.xml";
91
    private static final int TIME = 5;
92
    private static final String DOCID = "docid";
93
    private static final String DATAID = "dataid";
94
    
95
    /**
96
     * Constructor to build the test
97
     *
98
     * @param name the name of the test method
99
     */
100
    public MetacatClientTest(String name)
101
    {
102
        super(name);
103
        // prefix is a generalization of the term 'scope' which is the beginning part of an identifier
104
        // because of the getLatestDocid() test, we need to make sure that prefix (which is used as scope)
105
        // is specific to these tests, and that docids are sequentially assigned.
106
        // (so keep this value for prefix, or make it more specific!)
107
        prefix = "metacatClientTest";
108
        newdocid = generateDocumentId();
109
    }
110

    
111
    /**
112
     * Establish a testing framework by initializing appropriate objects
113
     */
114
    public void setUp()
115
    {
116
        try {
117
        	FileInputStream fis = new FileInputStream(testfile);
118
            testdocument = IOUtils.toString(fis);
119
        } catch (IOException ioe) {
120
            fail("Can't read test data to run the test: " + testfile);
121
        }
122

    
123
        try {
124
            debug("Test Metacat: " + metacatUrl);
125
            m = MetacatFactory.createMetacatConnection(metacatUrl);
126
        } catch (MetacatInaccessibleException mie) {
127
            System.err.println("Metacat is: " + metacatUrl);
128
            fail("Metacat connection failed." + mie.getMessage());
129
        }
130
    }
131

    
132
    /**
133
     * Release any objects after tests are complete
134
     */
135
    public void tearDown()
136
    {
137
    }
138

    
139
    /**
140
     * Create a suite of tests to be run together
141
     */
142
    public static Test suite()
143
    {
144
      TestSuite suite = new TestSuite();     
145
      suite.addTest(new MetacatClientTest("initialize"));
146
      suite.addTest(new MetacatClientTest("invalidLogin"));
147
      suite.addTest(new MetacatClientTest("logoutAndInvalidInsert"));
148
      suite.addTest(new MetacatClientTest("login"));
149
      suite.addTest(new MetacatClientTest("insert"));
150
      suite.addTest(new MetacatClientTest("getLastDocid"));  // needs to directly follow insert test!!
151
      suite.addTest(new MetacatClientTest("getNewestDocRevision"));  // (also tries to insert)
152
      suite.addTest(new MetacatClientTest("upload"));
153
      suite.addTest(new MetacatClientTest("upload_stream"));
154
      suite.addTest(new MetacatClientTest("invalidRead"));
155
      suite.addTest(new MetacatClientTest("read"));
156
      suite.addTest(new MetacatClientTest("query"));
157
      suite.addTest(new MetacatClientTest("queryWithQformat"));
158
      suite.addTest(new MetacatClientTest("invalidUpdate"));
159
      suite.addTest(new MetacatClientTest("update"));
160
      suite.addTest(new MetacatClientTest("invalidDelete"));
161
      suite.addTest(new MetacatClientTest("delete"));
162
      suite.addTest(new MetacatClientTest("inaccessibleMetacat"));
163
      suite.addTest(new MetacatClientTest("reuseSession"));
164
      suite.addTest(new MetacatClientTest("reuseInvalidSession"));
165
      suite.addTest(new MetacatClientTest("insertSpatialDocs"));
166
      suite.addTest(new MetacatClientTest("getAccessControl"));
167
      suite.addTest(new MetacatClientTest("getAccessControlFromDocWithoutAccess"));
168
      return suite;
169
  }
170

    
171
    /**
172
     * Run an initial test that always passes to check that the test
173
     * harness is working.
174
     */
175
    public void initialize()
176
    {
177
        assertTrue(1 == 1);
178
    }
179

    
180
    /**
181
     * Test the login() function with valid credentials
182
     */
183
    public void login()
184
    {
185
        debug("\nStarting login test...");
186
        // Try a valid login
187
        try {
188
            String response = m.login(username, password);
189
            debug("login(): response=" + response);
190
            assertTrue(response != null);
191
            assertTrue(response.indexOf("<login>") != -1);
192
            String sessionId = m.getSessionId();
193
            debug("login(): Session ID=" + m.getSessionId());
194
            assertTrue(sessionId != null);
195
            assertTrue(response.indexOf(m.getSessionId()) != -1);
196
        } catch (MetacatAuthException mae) {
197
            fail("Authorization failed:\n" + mae.getMessage());
198
        } catch (MetacatInaccessibleException mie) {
199
            fail("Metacat Inaccessible:\n" + mie.getMessage());
200
        }
201
    }
202

    
203
    /**
204
     * Test the login() function with INVALID credentials
205
     */
206
    public void invalidLogin()
207
    {
208
        debug("\nStarting invalidLogin test...");
209
        // Try an invalid login
210
        try {
211
            m.login(username, failpass);
212
            fail("Authorization should have failed.");
213
        } catch (MetacatAuthException mae) {
214
            assertTrue(1 == 1);
215
        } catch (MetacatInaccessibleException mie) {
216
            fail("Metacat Inaccessible:\n" + mie.getMessage());
217
        }
218
    }
219

    
220
    /**
221
     * Test the logout() function. When logout, user will be public, it couldn't
222
     * insert a document.
223
     */
224
    public void logoutAndInvalidInsert()
225
    {
226
       debug("\nStarting logoutAndInvalidInsert test...");
227
       try {
228
            String identifier = newdocid + ".1";
229
            m.login(username, password);
230
            m.logout();
231
            String response = m.insert(identifier,
232
                    new StringReader(testdocument), null);
233
            debug("logoutAndInvalidInsert(): Response in logout="+response);
234
            assertTrue(response.indexOf("<success>") == -1);
235
        } catch (MetacatAuthException mae) {
236
            fail("Authorization failed:\n" + mae.getMessage());
237
        } catch (MetacatInaccessibleException mie) {
238
            fail("Metacat Inaccessible:\n" + mie.getMessage());
239
        } catch (InsufficientKarmaException ike) {
240
            fail("Insufficient karma:\n" + ike.getMessage());
241
        } catch (MetacatException me) {
242
            if(me.getMessage().
243
              indexOf("Permission denied for user public inser") == -1){
244
               fail("Metacat Error:\n" + me.getMessage());
245
           }
246
        } catch (Exception e) {
247
            fail("General exception:\n" + e.getMessage());
248
        }
249
    }
250

    
251
    /**
252
     * Test the read() function with a known document
253
     */
254
    public void read()
255
    {
256
        debug("\nStarting read test...");
257
        try {
258
            m.login(username, password);
259
            String docid = readIdFromFile(DOCID);
260
            debug("docid=" + docid);
261
            InputStream is = m.read(docid+".1");
262
            String doc = IOUtils.toString(is);
263
            // why oh why were we adding a newline??
264
            //doc = doc +"\n";
265
            if (!doc.equals(testdocument)) {
266
                debug("doc         :" + doc + "EOF");
267
                debug("testdocument:" + testdocument + "EOF");
268
            }
269
            assertTrue(doc.equals(testdocument));
270
        } catch (MetacatAuthException mae) {
271
            fail("Authorization failed:\n" + mae.getMessage());
272
        } catch (MetacatInaccessibleException mie) {
273
            fail("Metacat Inaccessible:\n" + mie.getMessage());
274
        } catch (Exception e) {
275
            fail("General exception:\n" + e.getMessage());
276
        }
277
    }
278

    
279
    /**
280
     * A user try to read a document which it doesn't have read permission
281
     */
282
    public void invalidRead()
283
    {
284
        debug("\nStarting invalidRead test...");
285
        try {
286
            m.login(anotheruser, anotherpassword);
287
            String docid = readIdFromFile(DOCID);
288
            Reader r = new InputStreamReader(m.read(docid+".1"));
289
            String doc = IOUtil.getAsString(r, true);
290
            assertTrue(doc.indexOf("<error>") != -1);
291
            debug("invalidRead(): doc="+ doc);
292
        } catch (MetacatAuthException mae) {
293
            fail("Authorization failed:\n" + mae.getMessage());
294
        } catch (MetacatInaccessibleException mie) {
295
            fail("Metacat Inaccessible:\n" + mie.getMessage());
296
        } catch (InsufficientKarmaException ike) {
297
            assertTrue(1 == 1);
298
        } catch (MetacatException e) {
299
            fail("Metacat exception:\n" + e.getMessage());
300
        } catch (IOException ioe) {
301
            fail("IO exception:\n" + ioe.getMessage());
302
        } catch (DocumentNotFoundException ne) {
303
            fail("DocumentNotFound exception:\n" + ne.getMessage());
304

    
305
        } catch(Exception e) {
306
            fail("Exception:\n" + e.getMessage());
307
        }
308
    }
309

    
310
    /**
311
     * Test the query() function with a known document
312
     */
313
    public void query()
314
    {
315
        debug("\nStarting query test...");
316
        try {
317
            m.login(username,password);
318
            FileReader fr = new FileReader(queryFile);
319
            Reader r = m.query(fr);
320
            String result = IOUtil.getAsString(r, true);
321
            debug("query(): Query result=\n" + result);
322
            String docid = readIdFromFile(DOCID);
323
            assertTrue(result.indexOf(docid+".1")!=-1);
324
            assertTrue(result.indexOf("<?xml")!=-1);
325
        } catch (MetacatAuthException mae) {
326
            fail("Authorization failed:\n" + mae.getMessage());
327
        } catch (MetacatInaccessibleException mie) {
328
            fail("Metacat Inaccessible:\n" + mie.getMessage());
329
        } catch (Exception e) {
330
            fail("General exception:\n" + e.getMessage());
331
        }
332
    }
333
    /**
334
     * Test the query() function with a known document
335
     */
336
    public void queryWithQformat()
337
    {
338
        debug("\nStarting queryWithQformat test...");
339
        try {
340
            m.login(username,password);
341
            FileReader fr = new FileReader(queryFile);
342
            String qformat = "knb";
343
            Reader r = m.query(fr, qformat);
344
            String result = IOUtil.getAsString(r, true);
345
            debug("queryWithQformat(): Query result=\n" + result);
346
            String docid = readIdFromFile(DOCID);
347
            assertTrue(result.indexOf(docid+".1")!=-1);
348
            assertTrue(result.indexOf("<html>")!=-1);
349
        } catch (MetacatAuthException mae) {
350
            fail("Authorization failed:\n" + mae.getMessage());
351
        } catch (MetacatInaccessibleException mie) {
352
            fail("Metacat Inaccessible:\n" + mie.getMessage());
353
        } catch (Exception e) {
354
            fail("General exception:\n" + e.getMessage());
355
        }
356
    }
357

    
358
    /**
359
     * Test the insert() function with a known document
360
     */
361
    public void insert()
362
    {
363
        debug("\nStarting insert test...");
364
        try {
365
            String identifier = newdocid + ".1";
366
            //write newdocid into file for persistance
367
            writeIdToFile(DOCID, newdocid);
368
            m.login(username, password);
369
            String response = m.insert(identifier,
370
                    new StringReader(testdocument), null);
371
            assertTrue(response.indexOf("<success>") != -1);
372
            assertTrue(response.indexOf(identifier) != -1);
373
            debug("insert(): response=" + response);
374

    
375
        } catch (MetacatAuthException mae) {
376
            fail("Authorization failed:\n" + mae.getMessage());
377
        } catch (MetacatInaccessibleException mie) {
378
            fail("Metacat Inaccessible:\n" + mie.getMessage());
379
        } catch (InsufficientKarmaException ike) {
380
            assertTrue(1 == 1);
381
            fail("Insufficient karma:\n" + ike.getMessage());
382
        } catch (MetacatException me) {
383
            fail("Metacat Error:\n" + me.getMessage());
384
        } catch (Exception e) {
385
            fail("General exception:\n" + e.getMessage());
386
        }
387
    }
388
    
389
    /**
390
     * Test to get access control part of a document
391
     */
392
    public void getAccessControl() {
393
      try {
394
        FileInputStream fis = new FileInputStream(testEMLWithAccess);
395
        String document = IOUtils.toString(fis);
396
        String identifier = newdocid + ".1";
397
        m.login(username, password);
398
        String response = m.insert(identifier,
399
                new StringReader(document), null);
400
        assertTrue(response.indexOf("<success>") != -1);
401
        assertTrue(response.indexOf(identifier) != -1);
402
        response = m.getAccessControl(identifier);
403
        //System.out.println("reponse is "+reponse);
404
        assertTrue(response.indexOf("<permission>read</permission>") != -1);
405
        assertTrue(response.indexOf("<principal>public</principal>") != -1);
406
    } catch (MetacatAuthException mae) {
407
        fail("Authorization failed:\n" + mae.getMessage());
408
    } catch (MetacatInaccessibleException mie) {
409
        fail("Metacat Inaccessible:\n" + mie.getMessage());
410
    } catch (InsufficientKarmaException ike) {
411
        assertTrue(1 == 1);
412
        fail("Insufficient karma:\n" + ike.getMessage());
413
    } catch (MetacatException me) {
414
        fail("Metacat Error:\n" + me.getMessage());
415
    } catch (Exception e) {
416
        fail("General exception:\n" + e.getMessage());
417
    }
418
     
419
  }
420
    
421
    /**
422
     * Test to get access control part of a document
423
     */
424
    public void getAccessControlFromDocWithoutAccess() {
425
      try {
426
        String identifier = newdocid + ".1";
427
        m.login(username, password);
428
        String response = m.insert(identifier,
429
                new StringReader(testdocument), null);
430
        assertTrue(response.indexOf("<success>") != -1);
431
        assertTrue(response.indexOf(identifier) != -1);
432
        response = m.getAccessControl(identifier);
433
        //System.out.println("the identifier is "+identifier);
434
        //System.out.println("reponse is "+response);
435
        assertTrue(response.indexOf("<permission>read</permission>") == -1);
436
        assertTrue(response.indexOf("<principal>public</principal>") == -1);
437
        assertTrue(response.indexOf("<access authSystem=") != -1);
438
    } catch (MetacatAuthException mae) {
439
        fail("Authorization failed:\n" + mae.getMessage());
440
    } catch (MetacatInaccessibleException mie) {
441
        fail("Metacat Inaccessible:\n" + mie.getMessage());
442
    } catch (InsufficientKarmaException ike) {
443
        assertTrue(1 == 1);
444
        fail("Insufficient karma:\n" + ike.getMessage());
445
    } catch (MetacatException me) {
446
        fail("Metacat Error:\n" + me.getMessage());
447
    } catch (Exception e) {
448
        fail("General exception:\n" + e.getMessage());
449
    }
450
     
451
  }
452

    
453
    /**
454
     * Test the upload() function with a data file.
455
     * 1. Insert version 1 successfully.
456
     * 2. Update version 2 successfully
457
     * 3. Update version 2 again and should be failed.
458
     */
459
    public void upload()
460
    {
461
        debug("\nStarting upload test...");
462
        try {
463
            newdocid = generateDocumentId();
464
            String identifier = newdocid + ".1";
465
            writeIdToFile(DATAID, newdocid);
466
            m.login(username, password);
467
            String response = m.upload(identifier,
468
                                     new File(onlinetestdatafile));
469
            assertTrue(response.indexOf("<success>") != -1);
470
            assertTrue(response.indexOf(identifier) != -1);
471
            identifier = newdocid +".2";
472
            response = m.upload(identifier,
473
                    new File(onlinetestdatafile));
474
            assertTrue(response.indexOf("<success>") != -1);
475
            assertTrue(response.indexOf(identifier) != -1);
476
            debug("upload(): response=" + response);
477
            //upload the same identifier again. it should return an error
478
            try
479
            {
480
                response = m.upload(identifier,
481
                      new File(onlinetestdatafile));
482
                fail("Metacat shouldn't successfully upload the same identifier twice "+response);
483
            }
484
            catch(Exception ee)
485
            {
486
                assertTrue(ee.getMessage().indexOf("<error>") != -1);
487
            }
488

    
489
        } catch (MetacatAuthException mae) {
490
            fail("Authorization failed:\n" + mae.getMessage());
491
        } catch (MetacatInaccessibleException mie) {
492
          mie.printStackTrace();
493
            fail("Metacat Inaccessible:\n" + mie.getMessage());
494
        } catch (InsufficientKarmaException ike) {
495
            assertTrue(1 == 1);
496
            fail("Insufficient karma:\n" + ike.getMessage());
497
        } catch (MetacatException me) {
498
            fail("Metacat Error:\n" + me.getMessage());
499
        } catch (Exception e) {
500
            fail("General exception:\n" + e.getMessage());
501
        }
502
    }
503
    
504

    
505

    
506
    /**
507
     * Test the upload() function by passing an InputStream
508
     */
509
    public void upload_stream()
510
    {
511
        debug("\nStarting upload_stream test...");
512
        try {
513
            newdocid = generateDocumentId();
514
            String identifier = newdocid + ".1";
515
            m.login(username, password);
516
            File testFile = new File(onlinetestdatafile);
517
            String response = m.upload(identifier, "onlineDataFile1",
518
                                       new FileInputStream(testFile),
519
                                       (int) testFile.length());
520

    
521
            assertTrue(response.indexOf("<success>") != -1);
522
            assertTrue(response.indexOf(identifier) != -1);
523
            identifier = newdocid + ".2";
524
            response = m.upload(identifier, "onlineDataFile1",
525
                    new FileInputStream(testFile),
526
                    (int) testFile.length());
527

    
528
           assertTrue(response.indexOf("<success>") != -1);
529
           assertTrue(response.indexOf(identifier) != -1);
530
           debug("upload_stream(): response=" + response);
531

    
532
        } catch (MetacatAuthException mae) {
533
            fail("Authorization failed:\n" + mae.getMessage());
534
        } catch (MetacatInaccessibleException mie) {
535
          mie.printStackTrace();
536
            fail("Metacat Inaccessible:\n" + mie.getMessage());
537
        } catch (InsufficientKarmaException ike) {
538
            assertTrue(1 == 1);
539
            fail("Insufficient karma:\n" + ike.getMessage());
540
        } catch (MetacatException me) {
541
            fail("Metacat Error:\n" + me.getMessage());
542
        } catch (Exception e) {
543
            fail("General exception:\n" + e.getMessage());
544
        }
545
    }
546

    
547
    /**
548
     * Test the invalidUpdate() function. A user try to update a document
549
     * which it doesn't have permission
550
     */
551
    public void invalidUpdate()
552
    {
553
        debug("\nStarting invalidUpdate test...");
554
        try {
555
        	String docid = readIdFromFile(DOCID);
556
            String identifier = docid + ".2";
557
            m.login(anotheruser, anotherpassword);
558
            String response = m.update(identifier,
559
                    new StringReader(testdocument), null);
560
            assertTrue(response.indexOf("<success>") == -1);
561

    
562
        } catch (MetacatAuthException mae) {
563
            fail("Authorization failed:\n" + mae.getMessage());
564
        } catch (MetacatInaccessibleException mie) {
565
            fail("Metacat Inaccessible:\n" + mie.getMessage());
566
        } catch (InsufficientKarmaException ike) {
567
            assertTrue(1 == 1);
568
        } catch (MetacatException me) {
569
            fail("Metacat Error:\n" + me.getMessage());
570
        } catch (Exception e) {
571
            fail("General exception:\n" + e.getMessage());
572
        }
573
    }
574

    
575
    /**
576
     * Test the update() function with a known document
577
     */
578
    public void update()
579
    {
580
        debug("\nStarting update test...");
581
        try {
582
        	String docid = readIdFromFile(DOCID);
583
            String identifier = docid + ".2";
584
            m.login(username, password);
585
            String response = m.update(identifier,
586
                    new StringReader(testdocument), null);
587
            assertTrue(response.indexOf("<success>") != -1);
588
            assertTrue(response.indexOf(identifier) != -1);
589
            debug("update(): response=" + response);
590

    
591
        } catch (MetacatAuthException mae) {
592
            fail("Authorization failed:\n" + mae.getMessage());
593
        } catch (MetacatInaccessibleException mie) {
594
            fail("Metacat Inaccessible:\n" + mie.getMessage());
595
        } catch (InsufficientKarmaException ike) {
596
            fail("Insufficient karma:\n" + ike.getMessage());
597
        } catch (MetacatException me) {
598
            fail("Metacat Error:\n" + me.getMessage());
599
        } catch (Exception e) {
600
            fail("General exception:\n" + e.getMessage());
601
        }
602
    }
603

    
604
    /**
605
     * A user try delete a document which it doesn't have permission
606
     */
607
    public void invalidDelete()
608
    {
609
        debug("\nStarting invalidDelete test...");
610
        try {
611
            String identifier = newdocid + ".2";
612
            m.login(anotheruser, anotherpassword);
613
            String response = m.delete(identifier);
614
            assertTrue(response.indexOf("<success>") == -1);
615
            debug("invalidDelete(): response=" + response);
616

    
617
        } catch (MetacatAuthException mae) {
618
            fail("Authorization failed:\n" + mae.getMessage());
619
        } catch (MetacatInaccessibleException mie) {
620
            fail("Metacat Inaccessible:\n" + mie.getMessage());
621
        } catch (InsufficientKarmaException ike) {
622
            assertTrue(1 == 1);
623
        } catch (MetacatException me) {
624
            assertTrue(1 == 1);
625
        } catch (Exception e) {
626
            fail("General exception:\n" + e.getMessage());
627
        }
628
    }
629

    
630
    /**
631
     * Test the delete() function with a known document
632
     */
633
    public void delete()
634
    {
635
        debug("\nStarting delete test...");
636
        try {
637
        	Thread.sleep(10000);
638
        	String docid = readIdFromFile(DOCID);
639
            String identifier = docid + ".2";
640
            m.login(username, password);
641
            String response = m.delete(identifier);
642
            assertTrue(response.indexOf("<success>") != -1);
643
            // delete the docid persistence file.
644
            deleteFile(DOCID);
645
            deleteFile(DATAID);
646
            debug("delete(): response=" + response);
647

    
648
        } catch (MetacatAuthException mae) {
649
            fail("Authorization failed:\n" + mae.getMessage());
650
        } catch (MetacatInaccessibleException mie) {
651
            fail("Metacat Inaccessible:\n" + mie.getMessage());
652
        } catch (InsufficientKarmaException ike) {
653
            fail("Insufficient karma:\n" + ike.getMessage());
654
        } catch (MetacatException me) {
655
            fail("Metacat Error:\n" + me.getMessage());
656
        } catch (Exception e) {
657
            fail("General exception:\n" + e.getMessage());
658
        }
659
    }
660

    
661
    /**
662
     * Test the to connect a wrong metacat url. Create a new metacat with a
663
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
664
     * exception, this is right.
665
     */
666
    public void inaccessibleMetacat()
667
    {
668
        debug("\nStarting inaccessibleMetacat test...");
669
        Metacat mWrong = null;
670
        try {
671
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
672
        } catch (MetacatInaccessibleException mie) {
673
            fail("Metacat Inaccessible:\n" + mie.getMessage());
674
        }
675

    
676
        try {
677
            mWrong.login(username, password);
678
        } catch (MetacatInaccessibleException mie) {
679
            assertTrue(1 == 1);
680
        } catch (MetacatAuthException mae) {
681
            fail("Authorization failed:\n" + mae.getMessage());
682
        }
683
    }
684

    
685
    /**
686
     * Try to perform an action that requires a session to be valid without
687
     * having logged in first by setting the sessionId from a previous
688
     * session.  Then insert a document.
689
     */
690
    public void reuseSession()
691
    {
692
        debug("\nStarting reuseSession test...");
693
        String oldSessionId = "";
694
        try {
695
        	debug("creating metacat connection to: " + metacatUrl);
696
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
697
        	debug("creating metacat connection with credentials: " + username + ":" + password);
698
            String response = mtemp.login(username, password);
699
            oldSessionId = mtemp.getSessionId();
700
            debug("preparing to reuse session with oldSessionId:" + oldSessionId);
701
        } catch (MetacatAuthException mae) {
702
            fail("Authorization failed:\n" + mae.getMessage());
703
        } catch (MetacatInaccessibleException mie) {
704
            System.err.println("Metacat is: " + metacatUrl);
705
            fail("Metacat connection failed." + mie.getMessage());
706
        }
707

    
708
        try {
709
            String identifier = generateDocumentId() + ".1";
710
            Metacat m2 = null;
711
            try {
712
            	debug("Creating second connection and logging out of it.");
713
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
714
                m2.login(username, password);
715
                m2.logout();
716
            } catch (MetacatInaccessibleException mie) {
717
                System.err.println("Could not connect to metacat at: " + metacatUrl 
718
                		+ " : " + mie.getMessage());
719
                fail("Metacat connection failed." + mie.getMessage());
720
            }
721
            m2.setSessionId(oldSessionId);
722
            debug("Reusing second session with session id :" + m2.getSessionId());
723
            String response = m2.insert(identifier,
724
                    new StringReader(testdocument), null);
725
            debug("Reuse second session insert response: " + response);
726
            assertTrue(response.indexOf("<success>") != -1);
727
        } catch (MetacatInaccessibleException mie) {
728
            fail("Metacat Inaccessible:\n" + mie.getMessage());
729
        } catch (InsufficientKarmaException ike) {
730
            fail("Insufficient karma:\n" + ike.getMessage());
731
        } catch (MetacatException me) {
732
            fail("Metacat Error:\n" + me.getMessage());
733
        } catch (Exception e) {
734
            fail("General exception:\n" + e.getMessage());
735
        }
736
    }
737

    
738
    /**
739
     * Try to perform an action that requires a session to be valid without
740
     * having logged in first, but use an invalid session identifier.
741
     * Then insert a document, which should fail.
742
     */
743
    public void reuseInvalidSession()
744
    {
745
        debug("\nStarting resuseInvalidSession test...");
746
        String oldSessionId = "foobar";
747
        try {
748
            String identifier = generateDocumentId() + ".1";
749
            Metacat m3 = null;
750
            try {
751
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
752
                m3.logout();
753
            } catch (MetacatInaccessibleException mie) {
754
                System.err.println("Metacat is: " + metacatUrl);
755
                fail("Metacat connection failed." + mie.getMessage());
756
            }
757
            debug("reuseInvalidSession(): SessionId (m3): " + m3.getSessionId());
758
            m3.setSessionId(oldSessionId);
759
            debug("reuseInvalidSession(): SessionId(m3 after set)=" + m3.getSessionId());
760
            debug("reuseInvalidSession(): identifier=" + identifier);
761
            String response = m3.insert(identifier,
762
                    new StringReader(testdocument), null);
763
            debug("reuseInvalidSession(): response=" + response);
764
            assertTrue(response.indexOf("<success>") == -1);
765
        } catch (MetacatInaccessibleException mie) {
766
            fail("Metacat Inaccessible:\n" + mie.getMessage());
767
        } catch (InsufficientKarmaException ike) {
768
            fail("Insufficient karma:\n" + ike.getMessage());
769
        } catch (MetacatException me) {
770
            if(me.getMessage().
771
               indexOf("Permission denied for user public inser") == -1){
772
                fail("Metacat Error:\n" + me.getMessage());
773
            }
774
        } catch (Exception e) {
775
            fail("General exception:\n" + e.getMessage());
776
        }
777
    }
778
    
779
   /**
780
    * Get the most recent document id for a given scope and be sure
781
    * that it matches the one we last inserted. Assumes this test is run
782
    * immediately following a successful insert() test, AND that the docid
783
    * inserted has the maximal numerical value.
784
    */
785
   public void getLastDocid()
786
   {
787
       debug("\nStarting getLastDocid test...");
788
       try {
789
           Metacat m3 = null;
790
           try {
791
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
792
           } catch (MetacatInaccessibleException mie) {
793
               System.err.println("Metacat is: " + metacatUrl);
794
               fail("Metacat connection failed." + mie.getMessage());
795
           }
796
           String lastId = m3.getLastDocid(prefix);
797
           
798
           debug("getLastDocid(): Scope = '"+ prefix + "', Last Id = " + lastId);
799
           
800
           //get docid from file
801
           String docid = readIdFromFile(DOCID);
802
           debug("getLastDocid(): File Id = " + docid + ".1");
803
           assertTrue(lastId.equals(docid + ".1"));
804
       } catch (MetacatException me) {
805
           fail("Metacat Error:\n" + me.getMessage());
806
       } catch (Exception e) {
807
           fail("General exception:\n" + e.getMessage());
808
       }
809
   }
810

    
811
   /**
812
    * Try to perform an action that requires a session to be valid without
813
    * having logged in first, but use an invalid session identifier.
814
    * Then insert a document, which should fail.
815
    */
816
   public void getNewestDocRevision()
817
   {
818
       debug("\nStarting getNewestDocRevision test...");
819
       try {
820
           
821
           Metacat m3 = null;
822
           try {
823
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
824
           } catch (MetacatInaccessibleException mie) {
825
               System.err.println("Metacat is: " + metacatUrl);
826
               fail("Metacat connection failed." + mie.getMessage());
827
           }
828
           // get docid from file
829
           String docid = readIdFromFile(DOCID);
830
           int revision = m3.getNewestDocRevision(docid);
831
           debug("getNewestDocRevision(): revision=" + revision);
832
           assertTrue(revision == 1);
833
       } catch (MetacatException me) {
834
           if(me.getMessage().
835
              indexOf("Permission denied for user public inser") == -1){
836
               fail("Metacat Error:\n" + me.getMessage());
837
           }
838
       } catch (Exception e) {
839
           fail("General exception:\n" + e.getMessage());
840
       }
841
   }
842
   
843
   /**
844
    * Try to insert a bunch of eml documents which contain spatial information
845
    * This test is used to try to find a bug in spatial part of metacat
846
    */
847
    public void insertSpatialDocs() throws IOException
848
    {
849
        debug("\nStarting insertSpatialDocs test...");
850
        
851
    	FileReader fr = new FileReader(spatialTestFile);
852
        String spatialtestdocument = IOUtil.getAsString(fr, true);
853
        debug("insertSpatialDocs(): the eml is "+spatialtestdocument);
854
    	for (int i=0; i<TIME; i++)
855
    	{
856
	    	try {
857
	    		Thread.sleep(20000);
858
	    		newdocid = generateDocumentId();
859
	            String identifier = newdocid + ".1";
860
	            debug("insertSpatialDocs(): the docid is "+identifier);
861
	            m.login(username, password);
862
	            String response = m.insert(identifier,
863
	                    new StringReader(spatialtestdocument), null);
864
	            assertTrue(response.indexOf("<success>") != -1);
865
	            assertTrue(response.indexOf(identifier) != -1);
866
	            Thread.sleep(20000);
867
	            identifier = newdocid +".2";
868
	            response = m.update(identifier,
869
	                    new StringReader(spatialtestdocument), null);
870
	            assertTrue(response.indexOf("<success>") != -1);
871
	            Thread.sleep(20000);
872
	            String response2 = m.delete(identifier);
873
	            assertTrue(response2.indexOf("<success>") != -1);
874
	            debug("insertSpatialDocs(): response=" + response);
875
	
876
	        } catch (MetacatAuthException mae) {
877
	            fail("Authorization failed:\n" + mae.getMessage());
878
	        } catch (MetacatInaccessibleException mie) {
879
	            fail("Metacat Inaccessible:\n" + mie.getMessage());
880
	        } catch (InsufficientKarmaException ike) {
881
	            assertTrue(1 == 1);
882
	            fail("Insufficient karma:\n" + ike.getMessage());
883
	        } catch (MetacatException me) {
884
	            fail("Metacat Error:\n" + me.getMessage());
885
	        } catch (Exception e) {
886
	            fail("General exception:\n" + e.getMessage());
887
	        }
888
    	}
889
    }
890
    
891
    /*
892
     * Write id to a file for persistance
893
     */
894
    private void writeIdToFile(String fileName, String id) throws Exception
895
    {
896
    	File file = new File(fileName);
897
    	StringReader reader = new StringReader(id);
898
    	FileWriter writer = new FileWriter(file);
899
    	char [] buffer = new char[1024];
900
    	int c = reader.read(buffer);
901
    	while (c != -1)
902
    	{
903
    		writer.write(buffer, 0, c);
904
    		c = reader.read(buffer);
905
    	}
906
    	writer.close();
907
    	reader.close();
908
    }
909
    
910
    /*
911
     * Read id from a given file
912
     */
913
    private String readIdFromFile(String fileName) throws Exception
914
    {
915
    	File file = new File(fileName);
916
    	FileReader reader = new FileReader(file);
917
    	StringWriter writer = new StringWriter();
918
    	char [] buffer = new char[1024];
919
    	int c = reader.read(buffer);
920
    	while (c != -1)
921
    	{
922
    		writer.write(buffer, 0, c);
923
    		c = reader.read(buffer);
924
    	}
925
    	reader.close();
926
    	return writer.toString();
927
    }
928
    
929
    /*
930
     * Delete the given file
931
     */
932
    private void deleteFile(String fileName) throws Exception
933
    {
934
    	File file = new File(fileName);
935
    	file.delete();
936
    }
937
}
    (1-1/1)