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: leinfelder $'
8
 *     '$Date: 2011-11-28 12:34:02 -0800 (Mon, 28 Nov 2011) $'
9
 * '$Revision: 6695 $'
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 onlinetestdatafile = "test/onlineDataFile1";
86
    private String queryFile = "test/query.xml";
87
    private String testdocument = "";
88
    private Metacat m;
89
    private String spatialTestFile = "test/spatialEml.xml";
90
    private static final int TIME = 5;
91
    private static final String DOCID = "docid";
92
    private static final String DATAID = "dataid";
93
    
94
    /**
95
     * Constructor to build the test
96
     *
97
     * @param name the name of the test method
98
     */
99
    public MetacatClientTest(String name)
100
    {
101
        super(name);
102
        // prefix is a generalization of the term 'scope' which is the beginning part of an identifier
103
        // because of the getLatestDocid() test, we need to make sure that prefix (which is used as scope)
104
        // is specific to these tests, and that docids are sequentially assigned.
105
        // (so keep this value for prefix, or make it more specific!)
106
        prefix = "metacatClientTest";
107
        newdocid = generateDocumentId();
108
    }
109

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

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

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

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

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

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

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

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

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

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

    
302
        } catch(Exception e) {
303
            fail("Exception:\n" + e.getMessage());
304
        }
305
    }
306

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

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

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

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

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

    
438

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

    
454
            assertTrue(response.indexOf("<success>") != -1);
455
            assertTrue(response.indexOf(identifier) != -1);
456
            identifier = newdocid + ".2";
457
            response = m.upload(identifier, "onlineDataFile1",
458
                    new FileInputStream(testFile),
459
                    (int) testFile.length());
460

    
461
           assertTrue(response.indexOf("<success>") != -1);
462
           assertTrue(response.indexOf(identifier) != -1);
463
           debug("upload_stream(): response=" + response);
464

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

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

    
495
        } catch (MetacatAuthException mae) {
496
            fail("Authorization failed:\n" + mae.getMessage());
497
        } catch (MetacatInaccessibleException mie) {
498
            fail("Metacat Inaccessible:\n" + mie.getMessage());
499
        } catch (InsufficientKarmaException ike) {
500
            assertTrue(1 == 1);
501
        } catch (MetacatException me) {
502
            fail("Metacat Error:\n" + me.getMessage());
503
        } catch (Exception e) {
504
            fail("General exception:\n" + e.getMessage());
505
        }
506
    }
507

    
508
    /**
509
     * Test the update() function with a known document
510
     */
511
    public void update()
512
    {
513
        debug("\nStarting update test...");
514
        try {
515
        	String docid = readIdFromFile(DOCID);
516
            String identifier = docid + ".2";
517
            m.login(username, password);
518
            String response = m.update(identifier,
519
                    new StringReader(testdocument), null);
520
            assertTrue(response.indexOf("<success>") != -1);
521
            assertTrue(response.indexOf(identifier) != -1);
522
            debug("update(): response=" + response);
523

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

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

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

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

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

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

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

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

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

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

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