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-07-18 10:02:28 -0700 (Fri, 18 Jul 2008) $'
9
 * '$Revision: 4145 $'
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.metacat.url");
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
            System.err.println("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
        // Try a valid login
182
        try {
183
            String response = m.login(username, password);
184
            //System.err.println("Login response: " + response);
185
            assertTrue(response != null);
186
            assertTrue(response.indexOf("<login>") != -1);
187
            String sessionId = m.getSessionId();
188
            //System.err.println("Session ID: " + m.getSessionId());
189
            assertTrue(sessionId != null);
190
            assertTrue(response.indexOf(m.getSessionId()) != -1);
191
        } catch (MetacatAuthException mae) {
192
            fail("Authorization failed:\n" + mae.getMessage());
193
        } catch (MetacatInaccessibleException mie) {
194
            fail("Metacat Inaccessible:\n" + mie.getMessage());
195
        }
196
    }
197

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

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

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

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

    
291
        } catch(Exception e) {
292
            fail("Exception:\n" + e.getMessage());
293
        }
294
    }
295

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

    
344
    /**
345
     * Test the insert() function with a known document
346
     */
347
    public void insert()
348
    {
349
        try {
350
            String identifier = newdocid + ".1";
351
            //write newdocid into file for persistance
352
            writeIdToFile(DOCID, newdocid);
353
            m.login(username, password);
354
            String response = m.insert(identifier,
355
                    new StringReader(testdocument), null);
356
            assertTrue(response.indexOf("<success>") != -1);
357
            assertTrue(response.indexOf(identifier) != -1);
358
            //System.err.println(response);
359

    
360
        } catch (MetacatAuthException mae) {
361
            fail("Authorization failed:\n" + mae.getMessage());
362
        } catch (MetacatInaccessibleException mie) {
363
            fail("Metacat Inaccessible:\n" + mie.getMessage());
364
        } catch (InsufficientKarmaException ike) {
365
            assertTrue(1 == 1);
366
            fail("Insufficient karma:\n" + ike.getMessage());
367
        } catch (MetacatException me) {
368
            fail("Metacat Error:\n" + me.getMessage());
369
        } catch (Exception e) {
370
            fail("General exception:\n" + e.getMessage());
371
        }
372
    }
373

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

    
409
        } catch (MetacatAuthException mae) {
410
            fail("Authorization failed:\n" + mae.getMessage());
411
        } catch (MetacatInaccessibleException mie) {
412
          mie.printStackTrace();
413
            fail("Metacat Inaccessible:\n" + mie.getMessage());
414
        } catch (InsufficientKarmaException ike) {
415
            assertTrue(1 == 1);
416
            fail("Insufficient karma:\n" + ike.getMessage());
417
        } catch (MetacatException me) {
418
            fail("Metacat Error:\n" + me.getMessage());
419
        } catch (Exception e) {
420
            fail("General exception:\n" + e.getMessage());
421
        }
422
    }
423
    
424

    
425

    
426
    /**
427
     * Test the upload() function by passing an InputStream
428
     */
429
    public void upload_stream()
430
    {
431
        try {
432
            newdocid = generateDocid();
433
            String identifier = newdocid + ".1";
434
            m.login(username, password);
435
            File testFile = new File(onlinetestdatafile);
436
            String response = m.upload(identifier, "onlineDataFile1",
437
                                       new FileInputStream(testFile),
438
                                       (int) testFile.length());
439

    
440
            assertTrue(response.indexOf("<success>") != -1);
441
            assertTrue(response.indexOf(identifier) != -1);
442
            identifier = newdocid + ".2";
443
            response = m.upload(identifier, "onlineDataFile1",
444
                    new FileInputStream(testFile),
445
                    (int) testFile.length());
446

    
447
           assertTrue(response.indexOf("<success>") != -1);
448
           assertTrue(response.indexOf(identifier) != -1);
449
            //System.err.println(response);
450

    
451
        } catch (MetacatAuthException mae) {
452
            fail("Authorization failed:\n" + mae.getMessage());
453
        } catch (MetacatInaccessibleException mie) {
454
          mie.printStackTrace();
455
            fail("Metacat Inaccessible:\n" + mie.getMessage());
456
        } catch (InsufficientKarmaException ike) {
457
            assertTrue(1 == 1);
458
            fail("Insufficient karma:\n" + ike.getMessage());
459
        } catch (MetacatException me) {
460
            fail("Metacat Error:\n" + me.getMessage());
461
        } catch (Exception e) {
462
            fail("General exception:\n" + e.getMessage());
463
        }
464
    }
465

    
466
    /**
467
     * Test the invalidUpdate() function. A user try to update a document
468
     * which it doesn't have permission
469
     */
470
    public void invalidUpdate()
471
    {
472
        try {
473
        	String docid = readIdFromFile(DOCID);
474
            String identifier = docid + ".2";
475
            m.login(anotheruser, anotherpassword);
476
            String response = m.update(identifier,
477
                    new StringReader(testdocument), null);
478
            assertTrue(response.indexOf("<success>") == -1);
479

    
480
        } catch (MetacatAuthException mae) {
481
            fail("Authorization failed:\n" + mae.getMessage());
482
        } catch (MetacatInaccessibleException mie) {
483
            fail("Metacat Inaccessible:\n" + mie.getMessage());
484
        } catch (InsufficientKarmaException ike) {
485
            assertTrue(1 == 1);
486
        } catch (MetacatException me) {
487
            fail("Metacat Error:\n" + me.getMessage());
488
        } catch (Exception e) {
489
            fail("General exception:\n" + e.getMessage());
490
        }
491
    }
492

    
493
    /**
494
     * Test the update() function with a known document
495
     */
496
    public void update()
497
    {
498
        try {
499
        	String docid = readIdFromFile(DOCID);
500
            String identifier = docid + ".2";
501
            m.login(username, password);
502
            String response = m.update(identifier,
503
                    new StringReader(testdocument), null);
504
            assertTrue(response.indexOf("<success>") != -1);
505
            assertTrue(response.indexOf(identifier) != -1);
506
            //System.err.println(response);
507

    
508
        } catch (MetacatAuthException mae) {
509
            fail("Authorization failed:\n" + mae.getMessage());
510
        } catch (MetacatInaccessibleException mie) {
511
            fail("Metacat Inaccessible:\n" + mie.getMessage());
512
        } catch (InsufficientKarmaException ike) {
513
            fail("Insufficient karma:\n" + ike.getMessage());
514
        } catch (MetacatException me) {
515
            fail("Metacat Error:\n" + me.getMessage());
516
        } catch (Exception e) {
517
            fail("General exception:\n" + e.getMessage());
518
        }
519
    }
520

    
521
    /**
522
     * A user try delete a document which it doesn't have permission
523
     */
524
    public void invalidDelete()
525
    {
526
        try {
527
            String identifier = newdocid + ".2";
528
            m.login(anotheruser, anotherpassword);
529
            String response = m.delete(identifier);
530
            assertTrue(response.indexOf("<success>") == -1);
531
            //System.err.println(response);
532

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

    
546
    /**
547
     * Test the delete() function with a known document
548
     */
549
    public void delete()
550
    {
551
        try {
552
        	Thread.sleep(10000);
553
        	String docid = readIdFromFile(DOCID);
554
            String identifier = docid + ".2";
555
            m.login(username, password);
556
            String response = m.delete(identifier);
557
            assertTrue(response.indexOf("<success>") != -1);
558
            // delete the docid persistence file.
559
            deleteFile(DOCID);
560
            deleteFile(DATAID);
561
            //System.err.println(response);
562

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

    
576
    /**
577
     * Test the to connect a wrong metacat url. Create a new metacat with a
578
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
579
     * exception, this is right.
580
     */
581
    public void inaccessibleMetacat()
582
    {
583
        Metacat mWrong = null;
584
        try {
585
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
586
        } catch (MetacatInaccessibleException mie) {
587
            fail("Metacat Inaccessible:\n" + mie.getMessage());
588
        }
589

    
590
        try {
591
            mWrong.login(username, password);
592
        } catch (MetacatInaccessibleException mie) {
593
            assertTrue(1 == 1);
594
        } catch (MetacatAuthException mae) {
595
            fail("Authorization failed:\n" + mae.getMessage());
596
        }
597
    }
598

    
599
    /**
600
     * Try to perform an action that requires a session to be valid without
601
     * having logged in first by setting the sessionId from a previous
602
     * session.  Then insert a document.
603
     */
604
    public void reuseSession()
605
    {
606
        String oldSessionId = "";
607
        try {
608
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
609
            String response = mtemp.login(username, password);
610
            oldSessionId = mtemp.getSessionId();
611
            //System.err.println("SessionId (mtemp): " + oldSessionId);
612
        } catch (MetacatAuthException mae) {
613
            fail("Authorization failed:\n" + mae.getMessage());
614
        } catch (MetacatInaccessibleException mie) {
615
            System.err.println("Metacat is: " + metacatUrl);
616
            fail("Metacat connection failed." + mie.getMessage());
617
        }
618

    
619
        try {
620
            String identifier = generateDocid() + ".1";
621
            Metacat m2 = null;
622
            try {
623
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
624
                m2.logout();
625
            } catch (MetacatInaccessibleException mie) {
626
                System.err.println("Metacat is: " + metacatUrl);
627
                fail("Metacat connection failed." + mie.getMessage());
628
            }
629
            System.err.println("SessionId (m2): " + m2.getSessionId());
630
            m2.setSessionId(oldSessionId);
631
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
632
            String response = m2.insert(identifier,
633
                    new StringReader(testdocument), null);
634
            System.err.println("Reuse Insert response: " + response);
635
            assertTrue(response.indexOf("<success>") != -1);
636
        } catch (MetacatInaccessibleException mie) {
637
            fail("Metacat Inaccessible:\n" + mie.getMessage());
638
        } catch (InsufficientKarmaException ike) {
639
            fail("Insufficient karma:\n" + ike.getMessage());
640
        } catch (MetacatException me) {
641
            fail("Metacat Error:\n" + me.getMessage());
642
        } catch (Exception e) {
643
            fail("General exception:\n" + e.getMessage());
644
        }
645
    }
646

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

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

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