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: 2008-08-22 16:29:24 -0700 (Fri, 22 Aug 2008) $'
9
 * '$Revision: 4303 $'
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.DocumentImpl;
43
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
44
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
45
import edu.ucsb.nceas.metacat.client.Metacat;
46
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
47
import edu.ucsb.nceas.metacat.client.MetacatException;
48
import edu.ucsb.nceas.metacat.client.MetacatFactory;
49
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
50
import edu.ucsb.nceas.metacat.service.PropertyService;
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
            debug("read(): doc=" + doc);
260
            assertTrue(doc.equals(testdocument));
261
        } catch (MetacatAuthException mae) {
262
            fail("Authorization failed:\n" + mae.getMessage());
263
        } catch (MetacatInaccessibleException mie) {
264
            fail("Metacat Inaccessible:\n" + mie.getMessage());
265
        } catch (Exception e) {
266
            fail("General exception:\n" + e.getMessage());
267
        }
268
    }
269

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

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

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

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

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

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

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

    
432

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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