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-06 21:25:34 -0700 (Sun, 06 Jul 2008) $'
9
 * '$Revision: 4080 $'
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.metacat.DocumentImpl;
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.service.PropertyService;
50
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
51
import edu.ucsb.nceas.metacat.util.SystemUtil;
52
import edu.ucsb.nceas.utilities.IOUtil;
53
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
54
import junit.framework.Test;
55
import junit.framework.TestCase;
56
import junit.framework.TestSuite;
57
import java.io.FileInputStream;
58

    
59
import org.apache.log4j.Logger;
60

    
61
/**
62
 * A JUnit test for testing Step class processing
63
 */
64
public class MetacatClientTest extends TestCase
65
{
66

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

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

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

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

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

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

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

    
200
    /**
201
     * Test the login() function with INVALID credentials
202
     */
203
    public void invalidLogin()
204
    {
205
        // 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
       try {
223
            String identifier = newdocid + ".1";
224
            m.login(username, password);
225
            m.logout();
226
            String response = m.insert(identifier,
227
                    new StringReader(testdocument), null);
228
            //System.err.println("Response in logout: "+response);
229
            assertTrue(response.indexOf("<success>") == -1);
230
        } catch (MetacatAuthException mae) {
231
            fail("Authorization failed:\n" + mae.getMessage());
232
        } catch (MetacatInaccessibleException mie) {
233
            fail("Metacat Inaccessible:\n" + mie.getMessage());
234
        } catch (InsufficientKarmaException ike) {
235
            fail("Insufficient karma:\n" + ike.getMessage());
236
        } catch (MetacatException me) {
237
            if(me.getMessage().
238
              indexOf("Permission denied for user public inser") == -1){
239
               fail("Metacat Error:\n" + me.getMessage());
240
           }
241
        } catch (Exception e) {
242
            fail("General exception:\n" + e.getMessage());
243
        }
244
    }
245

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

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

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

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

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

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

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

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

    
427

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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