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: rnahf $'
8
 *     '$Date: 2011-04-28 13:53:17 -0700 (Thu, 28 Apr 2011) $'
9
 * '$Revision: 6052 $'
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.InputStreamReader;
32
import java.io.IOException;
33
import java.io.Reader;
34
import java.io.StringReader;
35
import java.io.StringWriter;
36

    
37
import edu.ucsb.nceas.MCTestCase;
38
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
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.metacat.properties.PropertyService;
46
import edu.ucsb.nceas.utilities.IOUtil;
47
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
48
import junit.framework.Test;
49
import junit.framework.TestSuite;
50
import java.io.FileInputStream;
51

    
52

    
53
/**
54
 * A JUnit test for testing Step class processing
55
 */
56
public class MetacatClientTest extends MCTestCase
57
{
58

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

    
107
    /**
108
     * Establish a testing framework by initializing appropriate objects
109
     */
110
    public void setUp()
111
    {
112
        try {
113
            FileReader fr = new FileReader(testfile);
114
            testdocument = IOUtil.getAsString(fr, true);
115
        } catch (IOException ioe) {
116
            fail("Can't read test data to run the test: " + testfile);
117
        }
118

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

    
128
    /**
129
     * Release any objects after tests are complete
130
     */
131
    public void tearDown()
132
    {
133
    }
134

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

    
165
    /**
166
     * Run an initial test that always passes to check that the test
167
     * harness is working.
168
     */
169
    public void initialize()
170
    {
171
        assertTrue(1 == 1);
172
    }
173

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

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

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

    
245
    /**
246
     * Test the read() function with a known document
247
     */
248
    public void read()
249
    {
250
        debug("\nStarting read test...");
251
        try {
252
            m.login(username, password);
253
            String docid = readIdFromFile(DOCID);
254
            Reader r = new InputStreamReader(m.read(docid+".1"));
255
            String doc = IOUtil.getAsString(r, true);
256
            // why oh why were we adding a newline??
257
            //doc = doc +"\n";
258
            if (!doc.equals(testdocument)) {
259
                debug("doc         :" + doc + "EOF");
260
                debug("testdocument:" + testdocument + "EOF");
261
            }
262
            assertTrue(doc.equals(testdocument));
263
        } catch (MetacatAuthException mae) {
264
            fail("Authorization failed:\n" + mae.getMessage());
265
        } catch (MetacatInaccessibleException mie) {
266
            fail("Metacat Inaccessible:\n" + mie.getMessage());
267
        } catch (Exception e) {
268
            fail("General exception:\n" + e.getMessage());
269
        }
270
    }
271

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

    
298
        } catch(Exception e) {
299
            fail("Exception:\n" + e.getMessage());
300
        }
301
    }
302

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

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

    
368
        } catch (MetacatAuthException mae) {
369
            fail("Authorization failed:\n" + mae.getMessage());
370
        } catch (MetacatInaccessibleException mie) {
371
            fail("Metacat Inaccessible:\n" + mie.getMessage());
372
        } catch (InsufficientKarmaException ike) {
373
            assertTrue(1 == 1);
374
            fail("Insufficient karma:\n" + ike.getMessage());
375
        } catch (MetacatException me) {
376
            fail("Metacat Error:\n" + me.getMessage());
377
        } catch (Exception e) {
378
            fail("General exception:\n" + e.getMessage());
379
        }
380
    }
381

    
382
    /**
383
     * Test the upload() function with a data file.
384
     * 1. Insert version 1 successfully.
385
     * 2. Update version 2 successfully
386
     * 3. Update version 2 again and should be failed.
387
     */
388
    public void upload()
389
    {
390
        debug("\nStarting upload test...");
391
        try {
392
            newdocid = generateDocumentId();
393
            String identifier = newdocid + ".1";
394
            writeIdToFile(DATAID, newdocid);
395
            m.login(username, password);
396
            String response = m.upload(identifier,
397
                                     new File(onlinetestdatafile));
398
            assertTrue(response.indexOf("<success>") != -1);
399
            assertTrue(response.indexOf(identifier) != -1);
400
            identifier = newdocid +".2";
401
            response = m.upload(identifier,
402
                    new File(onlinetestdatafile));
403
            assertTrue(response.indexOf("<success>") != -1);
404
            assertTrue(response.indexOf(identifier) != -1);
405
            debug("upload(): response=" + response);
406
            //upload the same identifier again. it should return an error
407
            try
408
            {
409
                response = m.upload(identifier,
410
                      new File(onlinetestdatafile));
411
                fail("Metacat shouldn't successfully upload the same identifier twice "+response);
412
            }
413
            catch(Exception ee)
414
            {
415
                assertTrue(ee.getMessage().indexOf("<error>") != -1);
416
            }
417

    
418
        } catch (MetacatAuthException mae) {
419
            fail("Authorization failed:\n" + mae.getMessage());
420
        } catch (MetacatInaccessibleException mie) {
421
          mie.printStackTrace();
422
            fail("Metacat Inaccessible:\n" + mie.getMessage());
423
        } catch (InsufficientKarmaException ike) {
424
            assertTrue(1 == 1);
425
            fail("Insufficient karma:\n" + ike.getMessage());
426
        } catch (MetacatException me) {
427
            fail("Metacat Error:\n" + me.getMessage());
428
        } catch (Exception e) {
429
            fail("General exception:\n" + e.getMessage());
430
        }
431
    }
432
    
433

    
434

    
435
    /**
436
     * Test the upload() function by passing an InputStream
437
     */
438
    public void upload_stream()
439
    {
440
        debug("\nStarting upload_stream test...");
441
        try {
442
            newdocid = generateDocumentId();
443
            String identifier = newdocid + ".1";
444
            m.login(username, password);
445
            File testFile = new File(onlinetestdatafile);
446
            String response = m.upload(identifier, "onlineDataFile1",
447
                                       new FileInputStream(testFile),
448
                                       (int) testFile.length());
449

    
450
            assertTrue(response.indexOf("<success>") != -1);
451
            assertTrue(response.indexOf(identifier) != -1);
452
            identifier = newdocid + ".2";
453
            response = m.upload(identifier, "onlineDataFile1",
454
                    new FileInputStream(testFile),
455
                    (int) testFile.length());
456

    
457
           assertTrue(response.indexOf("<success>") != -1);
458
           assertTrue(response.indexOf(identifier) != -1);
459
           debug("upload_stream(): response=" + response);
460

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

    
476
    /**
477
     * Test the invalidUpdate() function. A user try to update a document
478
     * which it doesn't have permission
479
     */
480
    public void invalidUpdate()
481
    {
482
        debug("\nStarting invalidUpdate test...");
483
        try {
484
        	String docid = readIdFromFile(DOCID);
485
            String identifier = docid + ".2";
486
            m.login(anotheruser, anotherpassword);
487
            String response = m.update(identifier,
488
                    new StringReader(testdocument), null);
489
            assertTrue(response.indexOf("<success>") == -1);
490

    
491
        } catch (MetacatAuthException mae) {
492
            fail("Authorization failed:\n" + mae.getMessage());
493
        } catch (MetacatInaccessibleException mie) {
494
            fail("Metacat Inaccessible:\n" + mie.getMessage());
495
        } catch (InsufficientKarmaException ike) {
496
            assertTrue(1 == 1);
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
     * Test the update() function with a known document
506
     */
507
    public void update()
508
    {
509
        debug("\nStarting update test...");
510
        try {
511
        	String docid = readIdFromFile(DOCID);
512
            String identifier = docid + ".2";
513
            m.login(username, password);
514
            String response = m.update(identifier,
515
                    new StringReader(testdocument), null);
516
            assertTrue(response.indexOf("<success>") != -1);
517
            assertTrue(response.indexOf(identifier) != -1);
518
            debug("update(): response=" + response);
519

    
520
        } catch (MetacatAuthException mae) {
521
            fail("Authorization failed:\n" + mae.getMessage());
522
        } catch (MetacatInaccessibleException mie) {
523
            fail("Metacat Inaccessible:\n" + mie.getMessage());
524
        } catch (InsufficientKarmaException ike) {
525
            fail("Insufficient karma:\n" + ike.getMessage());
526
        } catch (MetacatException me) {
527
            fail("Metacat Error:\n" + me.getMessage());
528
        } catch (Exception e) {
529
            fail("General exception:\n" + e.getMessage());
530
        }
531
    }
532

    
533
    /**
534
     * A user try delete a document which it doesn't have permission
535
     */
536
    public void invalidDelete()
537
    {
538
        debug("\nStarting invalidDelete test...");
539
        try {
540
            String identifier = newdocid + ".2";
541
            m.login(anotheruser, anotherpassword);
542
            String response = m.delete(identifier);
543
            assertTrue(response.indexOf("<success>") == -1);
544
            debug("invalidDelete(): response=" + response);
545

    
546
        } catch (MetacatAuthException mae) {
547
            fail("Authorization failed:\n" + mae.getMessage());
548
        } catch (MetacatInaccessibleException mie) {
549
            fail("Metacat Inaccessible:\n" + mie.getMessage());
550
        } catch (InsufficientKarmaException ike) {
551
            assertTrue(1 == 1);
552
        } catch (MetacatException me) {
553
            assertTrue(1 == 1);
554
        } catch (Exception e) {
555
            fail("General exception:\n" + e.getMessage());
556
        }
557
    }
558

    
559
    /**
560
     * Test the delete() function with a known document
561
     */
562
    public void delete()
563
    {
564
        debug("\nStarting delete test...");
565
        try {
566
        	Thread.sleep(10000);
567
        	String docid = readIdFromFile(DOCID);
568
            String identifier = docid + ".2";
569
            m.login(username, password);
570
            String response = m.delete(identifier);
571
            assertTrue(response.indexOf("<success>") != -1);
572
            // delete the docid persistence file.
573
            deleteFile(DOCID);
574
            deleteFile(DATAID);
575
            debug("delete(): response=" + response);
576

    
577
        } catch (MetacatAuthException mae) {
578
            fail("Authorization failed:\n" + mae.getMessage());
579
        } catch (MetacatInaccessibleException mie) {
580
            fail("Metacat Inaccessible:\n" + mie.getMessage());
581
        } catch (InsufficientKarmaException ike) {
582
            fail("Insufficient karma:\n" + ike.getMessage());
583
        } catch (MetacatException me) {
584
            fail("Metacat Error:\n" + me.getMessage());
585
        } catch (Exception e) {
586
            fail("General exception:\n" + e.getMessage());
587
        }
588
    }
589

    
590
    /**
591
     * Test the to connect a wrong metacat url. Create a new metacat with a
592
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
593
     * exception, this is right.
594
     */
595
    public void inaccessibleMetacat()
596
    {
597
        debug("\nStarting inaccessibleMetacat test...");
598
        Metacat mWrong = null;
599
        try {
600
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
601
        } catch (MetacatInaccessibleException mie) {
602
            fail("Metacat Inaccessible:\n" + mie.getMessage());
603
        }
604

    
605
        try {
606
            mWrong.login(username, password);
607
        } catch (MetacatInaccessibleException mie) {
608
            assertTrue(1 == 1);
609
        } catch (MetacatAuthException mae) {
610
            fail("Authorization failed:\n" + mae.getMessage());
611
        }
612
    }
613

    
614
    /**
615
     * Try to perform an action that requires a session to be valid without
616
     * having logged in first by setting the sessionId from a previous
617
     * session.  Then insert a document.
618
     */
619
    public void reuseSession()
620
    {
621
        debug("\nStarting reuseSession test...");
622
        String oldSessionId = "";
623
        try {
624
        	debug("creating metacat connection to: " + metacatUrl);
625
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
626
        	debug("creating metacat connection with credentials: " + username + ":" + password);
627
            String response = mtemp.login(username, password);
628
            oldSessionId = mtemp.getSessionId();
629
            debug("preparing to reuse session with oldSessionId:" + oldSessionId);
630
        } catch (MetacatAuthException mae) {
631
            fail("Authorization failed:\n" + mae.getMessage());
632
        } catch (MetacatInaccessibleException mie) {
633
            System.err.println("Metacat is: " + metacatUrl);
634
            fail("Metacat connection failed." + mie.getMessage());
635
        }
636

    
637
        try {
638
            String identifier = generateDocumentId() + ".1";
639
            Metacat m2 = null;
640
            try {
641
            	debug("Creating second connection and logging out of it.");
642
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
643
                m2.login(username, password);
644
                m2.logout();
645
            } catch (MetacatInaccessibleException mie) {
646
                System.err.println("Could not connect to metacat at: " + metacatUrl 
647
                		+ " : " + mie.getMessage());
648
                fail("Metacat connection failed." + mie.getMessage());
649
            }
650
            m2.setSessionId(oldSessionId);
651
            debug("Reusing second session with session id :" + m2.getSessionId());
652
            String response = m2.insert(identifier,
653
                    new StringReader(testdocument), null);
654
            debug("Reuse second session insert response: " + response);
655
            assertTrue(response.indexOf("<success>") != -1);
656
        } catch (MetacatInaccessibleException mie) {
657
            fail("Metacat Inaccessible:\n" + mie.getMessage());
658
        } catch (InsufficientKarmaException ike) {
659
            fail("Insufficient karma:\n" + ike.getMessage());
660
        } catch (MetacatException me) {
661
            fail("Metacat Error:\n" + me.getMessage());
662
        } catch (Exception e) {
663
            fail("General exception:\n" + e.getMessage());
664
        }
665
    }
666

    
667
    /**
668
     * Try to perform an action that requires a session to be valid without
669
     * having logged in first, but use an invalid session identifier.
670
     * Then insert a document, which should fail.
671
     */
672
    public void reuseInvalidSession()
673
    {
674
        debug("\nStarting resuseInvalidSession test...");
675
        String oldSessionId = "foobar";
676
        try {
677
            String identifier = generateDocumentId() + ".1";
678
            Metacat m3 = null;
679
            try {
680
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
681
                m3.logout();
682
            } catch (MetacatInaccessibleException mie) {
683
                System.err.println("Metacat is: " + metacatUrl);
684
                fail("Metacat connection failed." + mie.getMessage());
685
            }
686
            debug("reuseInvalidSession(): SessionId (m3): " + m3.getSessionId());
687
            m3.setSessionId(oldSessionId);
688
            debug("reuseInvalidSession(): SessionId(m3 after set)=" + m3.getSessionId());
689
            debug("reuseInvalidSession(): identifier=" + identifier);
690
            String response = m3.insert(identifier,
691
                    new StringReader(testdocument), null);
692
            debug("reuseInvalidSession(): response=" + response);
693
            assertTrue(response.indexOf("<success>") == -1);
694
        } catch (MetacatInaccessibleException mie) {
695
            fail("Metacat Inaccessible:\n" + mie.getMessage());
696
        } catch (InsufficientKarmaException ike) {
697
            fail("Insufficient karma:\n" + ike.getMessage());
698
        } catch (MetacatException me) {
699
            if(me.getMessage().
700
               indexOf("Permission denied for user public inser") == -1){
701
                fail("Metacat Error:\n" + me.getMessage());
702
            }
703
        } catch (Exception e) {
704
            fail("General exception:\n" + e.getMessage());
705
        }
706
    }
707
    
708
   /**
709
    * Get the most recent document id for a given scope and be sure
710
    * that it matches the one we last inserted. Assumes this test is run
711
    * immediately following a successful insert() test, AND that the docid
712
    * inserted has the maximal numerical value.
713
    */
714
   public void getLastDocid()
715
   {
716
       debug("\nStarting getLastDocid test...");
717
       try {
718
           Metacat m3 = null;
719
           try {
720
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
721
           } catch (MetacatInaccessibleException mie) {
722
               System.err.println("Metacat is: " + metacatUrl);
723
               fail("Metacat connection failed." + mie.getMessage());
724
           }
725
           String lastId = m3.getLastDocid(prefix);
726
           
727
           debug("getLastDocid(): Scope = '"+ prefix + "', Last Id = " + lastId);
728
           
729
           //get docid from file
730
           String docid = readIdFromFile(DOCID);
731
           debug("getLastDocid(): File Id = " + docid + ".1");
732
           assertTrue(lastId.equals(docid + ".1"));
733
       } catch (MetacatException me) {
734
           fail("Metacat Error:\n" + me.getMessage());
735
       } catch (Exception e) {
736
           fail("General exception:\n" + e.getMessage());
737
       }
738
   }
739

    
740
   /**
741
    * Try to perform an action that requires a session to be valid without
742
    * having logged in first, but use an invalid session identifier.
743
    * Then insert a document, which should fail.
744
    */
745
   public void getNewestDocRevision()
746
   {
747
       debug("\nStarting getNewestDocRevision test...");
748
       try {
749
           
750
           Metacat m3 = null;
751
           try {
752
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
753
           } catch (MetacatInaccessibleException mie) {
754
               System.err.println("Metacat is: " + metacatUrl);
755
               fail("Metacat connection failed." + mie.getMessage());
756
           }
757
           // get docid from file
758
           String docid = readIdFromFile(DOCID);
759
           int revision = m3.getNewestDocRevision(docid);
760
           debug("getNewestDocRevision(): revision=" + revision);
761
           assertTrue(revision == 1);
762
       } catch (MetacatException me) {
763
           if(me.getMessage().
764
              indexOf("Permission denied for user public inser") == -1){
765
               fail("Metacat Error:\n" + me.getMessage());
766
           }
767
       } catch (Exception e) {
768
           fail("General exception:\n" + e.getMessage());
769
       }
770
   }
771
   
772
   /**
773
    * Try to insert a bunch of eml documents which contain spatial information
774
    * This test is used to try to find a bug in spatial part of metacat
775
    */
776
    public void insertSpatialDocs() throws IOException
777
    {
778
        debug("\nStarting insertSpatialDocs test...");
779
        
780
    	FileReader fr = new FileReader(spatialTestFile);
781
        String spatialtestdocument = IOUtil.getAsString(fr, true);
782
        debug("insertSpatialDocs(): the eml is "+spatialtestdocument);
783
    	for (int i=0; i<TIME; i++)
784
    	{
785
	    	try {
786
	    		Thread.sleep(20000);
787
	    		newdocid = generateDocumentId();
788
	            String identifier = newdocid + ".1";
789
	            debug("insertSpatialDocs(): the docid is "+identifier);
790
	            m.login(username, password);
791
	            String response = m.insert(identifier,
792
	                    new StringReader(spatialtestdocument), null);
793
	            assertTrue(response.indexOf("<success>") != -1);
794
	            assertTrue(response.indexOf(identifier) != -1);
795
	            Thread.sleep(20000);
796
	            identifier = newdocid +".2";
797
	            response = m.update(identifier,
798
	                    new StringReader(spatialtestdocument), null);
799
	            assertTrue(response.indexOf("<success>") != -1);
800
	            Thread.sleep(20000);
801
	            String response2 = m.delete(identifier);
802
	            assertTrue(response2.indexOf("<success>") != -1);
803
	            debug("insertSpatialDocs(): response=" + response);
804
	
805
	        } catch (MetacatAuthException mae) {
806
	            fail("Authorization failed:\n" + mae.getMessage());
807
	        } catch (MetacatInaccessibleException mie) {
808
	            fail("Metacat Inaccessible:\n" + mie.getMessage());
809
	        } catch (InsufficientKarmaException ike) {
810
	            assertTrue(1 == 1);
811
	            fail("Insufficient karma:\n" + ike.getMessage());
812
	        } catch (MetacatException me) {
813
	            fail("Metacat Error:\n" + me.getMessage());
814
	        } catch (Exception e) {
815
	            fail("General exception:\n" + e.getMessage());
816
	        }
817
    	}
818
    }
819
    
820
    /*
821
     * Write id to a file for persistance
822
     */
823
    private void writeIdToFile(String fileName, String id) throws Exception
824
    {
825
    	File file = new File(fileName);
826
    	StringReader reader = new StringReader(id);
827
    	FileWriter writer = new FileWriter(file);
828
    	char [] buffer = new char[1024];
829
    	int c = reader.read(buffer);
830
    	while (c != -1)
831
    	{
832
    		writer.write(buffer, 0, c);
833
    		c = reader.read(buffer);
834
    	}
835
    	writer.close();
836
    	reader.close();
837
    }
838
    
839
    /*
840
     * Read id from a given file
841
     */
842
    private String readIdFromFile(String fileName) throws Exception
843
    {
844
    	File file = new File(fileName);
845
    	FileReader reader = new FileReader(file);
846
    	StringWriter writer = new StringWriter();
847
    	char [] buffer = new char[1024];
848
    	int c = reader.read(buffer);
849
    	while (c != -1)
850
    	{
851
    		writer.write(buffer, 0, c);
852
    		c = reader.read(buffer);
853
    	}
854
    	reader.close();
855
    	return writer.toString();
856
    }
857
    
858
    /*
859
     * Delete the given file
860
     */
861
    private void deleteFile(String fileName) throws Exception
862
    {
863
    	File file = new File(fileName);
864
    	file.delete();
865
    }
866
}
    (1-1/1)