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: daigle $'
8
 *     '$Date: 2009-08-24 14:42:25 -0700 (Mon, 24 Aug 2009) $'
9
 * '$Revision: 5035 $'
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.IOException;
32
import java.io.Reader;
33
import java.io.StringReader;
34
import java.io.StringWriter;
35
import java.util.Calendar;
36
import java.util.Date;
37
import java.util.GregorianCalendar;
38
import java.util.SimpleTimeZone;
39
import java.util.TimeZone;
40

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

    
57
import org.apache.log4j.Logger;
58

    
59
/**
60
 * A JUnit test for testing Step class processing
61
 */
62
public class MetacatClientTest extends MCTestCase
63
{
64

    
65
    private String wrongMetacatUrl=
66
    	"http://somepalce.somewhere.com/some/servlet/metacat";
67
  
68
    private static String metacatUrl;
69
    private static String username;
70
	private static String password;
71
	private static String anotheruser;
72
	private static String anotherpassword;
73
	static {
74
		try {
75
		    metacatUrl = PropertyService.getProperty("test.metacatUrl");
76
			username = PropertyService.getProperty("test.mcUser");
77
			password = PropertyService.getProperty("test.mcPassword");
78
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
79
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
80
		} catch (PropertyNotFoundException pnfe) {
81
			System.err.println("Could not get property in static block: " 
82
					+ pnfe.getMessage());
83
		}
84
	}
85
    private String failpass = "uidfnkj43987yfdn";
86
    private String prefix = "test";
87
    private String newdocid = null;
88
    private String testfile = "test/jones.204.22.xml";
89
    private String onlinetestdatafile = "test/onlineDataFile1";
90
    private String queryFile = "test/query.xml";
91
    private String testdocument = "";
92
    private Metacat m;
93
    private String spatialTestFile = "test/spatialEml.xml";
94
    private static final int TIME = 30;
95
    private static final String DOCID = "docid";
96
    private static final String DATAID = "dataid";
97
    
98
    /**
99
     * Constructor to build the test
100
     *
101
     * @param name the name of the test method
102
     */
103
    public MetacatClientTest(String name)
104
    {
105
        super(name);
106
        newdocid = generateDocid();
107
    }
108

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
435

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
737
   /**
738
    * Try to perform an action that requires a session to be valid without
739
    * having logged in first, but use an invalid session identifier.
740
    * Then insert a document, which should fail.
741
    */
742
   public void getNewestDocRevision()
743
   {
744
       debug("\nStarting getNewestDocRevision test...");
745
       try {
746
           
747
           Metacat m3 = null;
748
           try {
749
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
750
           } catch (MetacatInaccessibleException mie) {
751
               System.err.println("Metacat is: " + metacatUrl);
752
               fail("Metacat connection failed." + mie.getMessage());
753
           }
754
           // get docid from file
755
           String docid = readIdFromFile(DOCID);
756
           int revision = m3.getNewestDocRevision(docid);
757
           debug("getNewestDocRevision(): revision=" + revision);
758
           assertTrue(revision == 1);
759
       } catch (MetacatException me) {
760
           if(me.getMessage().
761
              indexOf("Permission denied for user public inser") == -1){
762
               fail("Metacat Error:\n" + me.getMessage());
763
           }
764
       } catch (Exception e) {
765
           fail("General exception:\n" + e.getMessage());
766
       }
767
   }
768
   
769
   /**
770
    * Try to insert a bunch of eml documents which contain spatial information
771
    * This test is used to try to find a bug in spatial part of metacat
772
    */
773
    public void insertSpatialDocs() throws IOException
774
    {
775
        debug("\nStarting insertSpatialDocs test...");
776
        
777
    	FileReader fr = new FileReader(spatialTestFile);
778
        String spatialtestdocument = IOUtil.getAsString(fr, true);
779
        debug("insertSpatialDocs(): the eml is "+spatialtestdocument);
780
    	for (int i=0; i<TIME; i++)
781
    	{
782
	    	try {
783
	    		newdocid = generateDocid();
784
	            String identifier = newdocid + ".1";
785
	            debug("insertSpatialDocs(): the docid is "+identifier);
786
	            m.login(username, password);
787
	            String response = m.insert(identifier,
788
	                    new StringReader(spatialtestdocument), null);
789
	            assertTrue(response.indexOf("<success>") != -1);
790
	            assertTrue(response.indexOf(identifier) != -1);
791
	            Thread.sleep(8000);
792
	            identifier = newdocid +".2";
793
	            response = m.update(identifier,
794
	                    new StringReader(spatialtestdocument), null);
795
	            assertTrue(response.indexOf("<success>") != -1);
796
	            Thread.sleep(6000);
797
	            String response2 = m.delete(identifier);
798
	            assertTrue(response2.indexOf("<success>") != -1);
799
	            debug("insertSpatialDocs(): response=" + response);
800
	
801
	        } catch (MetacatAuthException mae) {
802
	            fail("Authorization failed:\n" + mae.getMessage());
803
	        } catch (MetacatInaccessibleException mie) {
804
	            fail("Metacat Inaccessible:\n" + mie.getMessage());
805
	        } catch (InsufficientKarmaException ike) {
806
	            assertTrue(1 == 1);
807
	            fail("Insufficient karma:\n" + ike.getMessage());
808
	        } catch (MetacatException me) {
809
	            fail("Metacat Error:\n" + me.getMessage());
810
	        } catch (Exception e) {
811
	            fail("General exception:\n" + e.getMessage());
812
	        }
813
    	}
814
    }
815
    
816
    /**
817
     * Create a hopefully unique docid for testing insert and update. Does
818
     * not include the 'revision' part of the id.
819
     *
820
     * @return a String docid based on the current date and time
821
     */
822
    private String generateDocid()
823
    {
824
	StringBuffer docid = new StringBuffer(prefix);
825
	docid.append(".");
826
		     
827
        // Create a calendar to get the date formatted properly
828
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
829
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
830
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);
831
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
832
        Calendar calendar = new GregorianCalendar(pdt);
833
        Date trialTime = new Date();
834
        calendar.setTime(trialTime);
835

    
836
	int time = 0; 
837
	
838
	docid.append(calendar.get(Calendar.YEAR));
839
	
840
	time = calendar.get(Calendar.DAY_OF_YEAR);
841
	if(time < 10){
842
		docid.append("0");
843
		docid.append("0");
844
		docid.append(time);
845
	} else if(time < 100) {
846
		docid.append("0");
847
		docid.append(time);
848
	} else {
849
		docid.append(time);
850
	}
851
	
852
	time = calendar.get(Calendar.HOUR_OF_DAY);
853
	if(time < 10){
854
		docid.append("0");
855
		docid.append(time);
856
	} else {
857
		docid.append(time);
858
	}
859
	
860
	time = calendar.get(Calendar.MINUTE);
861
	if(time < 10){
862
		docid.append("0");
863
		docid.append(time);
864
	} else {
865
		docid.append(time);
866
	}
867
	
868
	time = calendar.get(Calendar.SECOND);
869
	if(time < 10){
870
		docid.append("0");
871
		docid.append(time);
872
	} else {
873
		docid.append(time);
874
	}
875
    
876
	 //sometimes this number is not unique, so we append a random number
877
	int random = (new Double(Math.random()*100)).intValue();
878
	docid.append(random);
879
	
880
	return docid.toString();
881
    }
882
    
883
    /*
884
     * Write id to a file for persistance
885
     */
886
    private void writeIdToFile(String fileName, String id) throws Exception
887
    {
888
    	File file = new File(fileName);
889
    	StringReader reader = new StringReader(id);
890
    	FileWriter writer = new FileWriter(file);
891
    	char [] buffer = new char[1024];
892
    	int c = reader.read(buffer);
893
    	while (c != -1)
894
    	{
895
    		writer.write(buffer, 0, c);
896
    		c = reader.read(buffer);
897
    	}
898
    	writer.close();
899
    	reader.close();
900
    }
901
    
902
    /*
903
     * Read id from a given file
904
     */
905
    private String readIdFromFile(String fileName) throws Exception
906
    {
907
    	File file = new File(fileName);
908
    	FileReader reader = new FileReader(file);
909
    	StringWriter writer = new StringWriter();
910
    	char [] buffer = new char[1024];
911
    	int c = reader.read(buffer);
912
    	while (c != -1)
913
    	{
914
    		writer.write(buffer, 0, c);
915
    		c = reader.read(buffer);
916
    	}
917
    	reader.close();
918
    	return writer.toString();
919
    }
920
    
921
    /*
922
     * Delete the given file
923
     */
924
    private void deleteFile(String fileName) throws Exception
925
    {
926
    	File file = new File(fileName);
927
    	file.delete();
928
    }
929
}
    (1-1/1)