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: tao $'
8
 *     '$Date: 2007-11-06 17:29:09 -0800 (Tue, 06 Nov 2007) $'
9
 * '$Revision: 3588 $'
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.utilities.IOUtil;
50
import junit.framework.Test;
51
import junit.framework.TestCase;
52
import junit.framework.TestSuite;
53
import java.io.FileInputStream;
54

    
55
import org.apache.log4j.Logger;
56

    
57
/**
58
 * A JUnit test for testing Step class processing
59
 */
60
public class MetacatClientTest extends TestCase
61
{
62
    private String metacatUrl = "@systemidserver@@servlet-path@";
63
    private String wrongMetacatUrl=
64
                    "http://somepalce.somewhere.com/some/servlet/metacat";
65
    private String username = "@mcuser@";
66
    private String password = "@mcpassword@";
67
    private String anotheruser = "@mcanotheruser@";
68
    private String anotherpassword = "@mcanotherpassword@";
69
    private String failpass = "uidfnkj43987yfdn";
70
    private String prefix = "test";
71
    private String newdocid = null;
72
    private String testfile = "test/jones.204.22.xml";
73
    private String onlinetestdatafile = "test/onlineDataFile1";
74
    private String queryFile = "test/query.xml";
75
    private String testdocument = "";
76
    private Metacat m;
77
    private String spatialTestFile = "test/spatialEml.xml";
78
    private static final int TIME = 30;
79
    private static final String DOCID = "docid";
80
    private static final String DATAID = "dataid";
81
    
82
    /**
83
     * Constructor to build the test
84
     *
85
     * @param name the name of the test method
86
     */
87
    public MetacatClientTest(String name)
88
    {
89
        super(name);
90
        newdocid = generateDocid();
91
    }
92

    
93
    /**
94
     * Establish a testing framework by initializing appropriate objects
95
     */
96
    public void setUp()
97
    {
98
        try {
99
            FileReader fr = new FileReader(testfile);
100
            testdocument = IOUtil.getAsString(fr, true);
101
        } catch (IOException ioe) {
102
            fail("Can't read test data to run the test: " + testfile);
103
        }
104

    
105
        try {
106
            System.err.println("Test Metacat: " + metacatUrl);
107
            m = MetacatFactory.createMetacatConnection(metacatUrl);
108
        } catch (MetacatInaccessibleException mie) {
109
            System.err.println("Metacat is: " + metacatUrl);
110
            fail("Metacat connection failed." + mie.getMessage());
111
        }
112
    }
113

    
114
    /**
115
     * Release any objects after tests are complete
116
     */
117
    public void tearDown()
118
    {
119
    }
120

    
121
    /**
122
     * Create a suite of tests to be run together
123
     */
124
    public static Test suite()
125
    {
126
      TestSuite suite = new TestSuite();
127
      suite.addTest(new MetacatClientTest("initialize"));
128
      suite.addTest(new MetacatClientTest("invalidLogin"));
129
      suite.addTest(new MetacatClientTest("logoutAndInvalidInsert"));
130
      suite.addTest(new MetacatClientTest("login"));
131
      suite.addTest(new MetacatClientTest("insert"));
132
      suite.addTest(new MetacatClientTest("getNewestDocRevision"));
133
      suite.addTest(new MetacatClientTest("getLastDocid"));
134
      suite.addTest(new MetacatClientTest("upload"));
135
      suite.addTest(new MetacatClientTest("upload_stream"));
136
      suite.addTest(new MetacatClientTest("invalidRead"));
137
      suite.addTest(new MetacatClientTest("read"));
138
      suite.addTest(new MetacatClientTest("query"));
139
      suite.addTest(new MetacatClientTest("queryWithQformat"));
140
      suite.addTest(new MetacatClientTest("invalidUpdate"));
141
      suite.addTest(new MetacatClientTest("update"));
142
      suite.addTest(new MetacatClientTest("invalidDelete"));
143
      suite.addTest(new MetacatClientTest("delete"));
144
      suite.addTest(new MetacatClientTest("inaccessibleMetacat"));
145
      suite.addTest(new MetacatClientTest("reuseSession"));
146
      suite.addTest(new MetacatClientTest("reuseInvalidSession"));
147
      //suite.addTest(new MetacatClientTest("insertSpatialDocs"));
148
      return suite;
149
  }
150

    
151
    /**
152
     * Run an initial test that always passes to check that the test
153
     * harness is working.
154
     */
155
    public void initialize()
156
    {
157
        assertTrue(1 == 1);
158
    }
159

    
160
    /**
161
     * Test the login() function with valid credentials
162
     */
163
    public void login()
164
    {
165
        // Try a valid login
166
        try {
167
            String response = m.login(username, password);
168
            //System.err.println("Login response: " + response);
169
            assertTrue(response != null);
170
            assertTrue(response.indexOf("<login>") != -1);
171
            String sessionId = m.getSessionId();
172
            //System.err.println("Session ID: " + m.getSessionId());
173
            assertTrue(sessionId != null);
174
            assertTrue(response.indexOf(m.getSessionId()) != -1);
175
        } catch (MetacatAuthException mae) {
176
            fail("Authorization failed:\n" + mae.getMessage());
177
        } catch (MetacatInaccessibleException mie) {
178
            fail("Metacat Inaccessible:\n" + mie.getMessage());
179
        }
180
    }
181

    
182
    /**
183
     * Test the login() function with INVALID credentials
184
     */
185
    public void invalidLogin()
186
    {
187
        // Try an invalid login
188
        try {
189
            m.login(username, failpass);
190
            fail("Authorization should have failed.");
191
        } catch (MetacatAuthException mae) {
192
            assertTrue(1 == 1);
193
        } catch (MetacatInaccessibleException mie) {
194
            fail("Metacat Inaccessible:\n" + mie.getMessage());
195
        }
196
    }
197

    
198
    /**
199
     * Test the logout() function. When logout, user will be public, it couldn't
200
     * insert a document.
201
     */
202
    public void logoutAndInvalidInsert()
203
    {
204
       try {
205
            String identifier = newdocid + ".1";
206
            m.login(username, password);
207
            m.logout();
208
            String response = m.insert(identifier,
209
                    new StringReader(testdocument), null);
210
            //System.err.println("Response in logout: "+response);
211
            assertTrue(response.indexOf("<success>") == -1);
212
        } catch (MetacatAuthException mae) {
213
            fail("Authorization failed:\n" + mae.getMessage());
214
        } catch (MetacatInaccessibleException mie) {
215
            fail("Metacat Inaccessible:\n" + mie.getMessage());
216
        } catch (InsufficientKarmaException ike) {
217
            fail("Insufficient karma:\n" + ike.getMessage());
218
        } catch (MetacatException me) {
219
            if(me.getMessage().
220
              indexOf("Permission denied for user public inser") == -1){
221
               fail("Metacat Error:\n" + me.getMessage());
222
           }
223
        } catch (Exception e) {
224
            fail("General exception:\n" + e.getMessage());
225
        }
226
    }
227

    
228
    /**
229
     * Test the read() function with a known document
230
     */
231
    public void read()
232
    {
233
        try {
234
            m.login(username, password);
235
            String docid = readIdFromFile(DOCID);
236
            Reader r = m.read(docid+".1");
237
            String doc = IOUtil.getAsString(r, true);
238
            doc = doc +"\n";
239
            //System.err.println(doc);
240
            assertTrue(doc.equals(testdocument));
241
        } catch (MetacatAuthException mae) {
242
            fail("Authorization failed:\n" + mae.getMessage());
243
        } catch (MetacatInaccessibleException mie) {
244
            fail("Metacat Inaccessible:\n" + mie.getMessage());
245
        } catch (Exception e) {
246
            fail("General exception:\n" + e.getMessage());
247
        }
248
    }
249

    
250
    /**
251
     * A user try to read a document which it doesn't have read permission
252
     */
253
    public void invalidRead()
254
    {
255
        try {
256
            m.login(anotheruser, anotherpassword);
257
            String docid = readIdFromFile(DOCID);
258
            Reader r = m.read(docid+".1");
259
            String doc = IOUtil.getAsString(r, true);
260
            assertTrue(doc.indexOf("<error>") != -1);
261
            //System.err.println(doc);
262
        } catch (MetacatAuthException mae) {
263
            fail("Authorization failed:\n" + mae.getMessage());
264
        } catch (MetacatInaccessibleException mie) {
265
            fail("Metacat Inaccessible:\n" + mie.getMessage());
266
        } catch (InsufficientKarmaException ike) {
267
            assertTrue(1 == 1);
268
        } catch (MetacatException e) {
269
            fail("Metacat exception:\n" + e.getMessage());
270
        } catch (IOException ioe) {
271
            fail("IO exception:\n" + ioe.getMessage());
272
        } catch (DocumentNotFoundException ne) {
273
            fail("DocumentNotFound exception:\n" + ne.getMessage());
274

    
275
        } catch(Exception e) {
276
            fail("Exception:\n" + e.getMessage());
277
        }
278
    }
279

    
280
    /**
281
     * Test the query() function with a known document
282
     */
283
    public void query()
284
    {
285
        try {
286
            m.login(username,password);
287
            FileReader fr = new FileReader(queryFile);
288
            Reader r = m.query(fr);
289
            //System.err.println("Starting query...");
290
            String result = IOUtil.getAsString(r, true);
291
            System.err.println("Query result:\n" + result);
292
            String docid = readIdFromFile(DOCID);
293
            assertTrue(result.indexOf(docid+".1")!=-1);
294
            assertTrue(result.indexOf("<?xml")!=-1);
295
        } catch (MetacatAuthException mae) {
296
            fail("Authorization failed:\n" + mae.getMessage());
297
        } catch (MetacatInaccessibleException mie) {
298
            fail("Metacat Inaccessible:\n" + mie.getMessage());
299
        } catch (Exception e) {
300
            fail("General exception:\n" + e.getMessage());
301
        }
302
    }
303
    /**
304
     * Test the query() function with a known document
305
     */
306
    public void queryWithQformat()
307
    {
308
        try {
309
            m.login(username,password);
310
            FileReader fr = new FileReader(queryFile);
311
            String qformat = "knb";
312
            Reader r = m.query(fr, qformat);
313
            //System.err.println("Starting query...");
314
            String result = IOUtil.getAsString(r, true);
315
            System.err.println("Query result:\n" + result);
316
            String docid = readIdFromFile(DOCID);
317
            assertTrue(result.indexOf(docid+".1")!=-1);
318
            assertTrue(result.indexOf("<html>")!=-1);
319
        } catch (MetacatAuthException mae) {
320
            fail("Authorization failed:\n" + mae.getMessage());
321
        } catch (MetacatInaccessibleException mie) {
322
            fail("Metacat Inaccessible:\n" + mie.getMessage());
323
        } catch (Exception e) {
324
            fail("General exception:\n" + e.getMessage());
325
        }
326
    }
327

    
328
    /**
329
     * Test the insert() function with a known document
330
     */
331
    public void insert()
332
    {
333
        try {
334
            String identifier = newdocid + ".1";
335
            //write newdocid into file for persistance
336
            writeIdToFile(DOCID, newdocid);
337
            m.login(username, password);
338
            String response = m.insert(identifier,
339
                    new StringReader(testdocument), null);
340
            assertTrue(response.indexOf("<success>") != -1);
341
            assertTrue(response.indexOf(identifier) != -1);
342
            //System.err.println(response);
343

    
344
        } catch (MetacatAuthException mae) {
345
            fail("Authorization failed:\n" + mae.getMessage());
346
        } catch (MetacatInaccessibleException mie) {
347
            fail("Metacat Inaccessible:\n" + mie.getMessage());
348
        } catch (InsufficientKarmaException ike) {
349
            assertTrue(1 == 1);
350
            fail("Insufficient karma:\n" + ike.getMessage());
351
        } catch (MetacatException me) {
352
            fail("Metacat Error:\n" + me.getMessage());
353
        } catch (Exception e) {
354
            fail("General exception:\n" + e.getMessage());
355
        }
356
    }
357

    
358
    /**
359
     * Test the upload() function with a known document
360
     */
361
    public void upload()
362
    {
363
        try {
364
            newdocid = generateDocid();
365
            String identifier = newdocid + ".1";
366
            writeIdToFile(DATAID, newdocid);
367
            m.login(username, password);
368
            String response = m.upload(identifier,
369
                                     new File(onlinetestdatafile));
370
            assertTrue(response.indexOf("<success>") != -1);
371
            assertTrue(response.indexOf(identifier) != -1);
372
            identifier = newdocid +".2";
373
            response = m.upload(identifier,
374
                    new File(onlinetestdatafile));
375
            assertTrue(response.indexOf("<success>") != -1);
376
            assertTrue(response.indexOf(identifier) != -1);
377
            //System.err.println(response);
378

    
379
        } catch (MetacatAuthException mae) {
380
            fail("Authorization failed:\n" + mae.getMessage());
381
        } catch (MetacatInaccessibleException mie) {
382
          mie.printStackTrace();
383
            fail("Metacat Inaccessible:\n" + mie.getMessage());
384
        } catch (InsufficientKarmaException ike) {
385
            assertTrue(1 == 1);
386
            fail("Insufficient karma:\n" + ike.getMessage());
387
        } catch (MetacatException me) {
388
            fail("Metacat Error:\n" + me.getMessage());
389
        } catch (Exception e) {
390
            fail("General exception:\n" + e.getMessage());
391
        }
392
    }
393

    
394
    /**
395
     * Test the upload() function by passing an InputStream
396
     */
397
    public void upload_stream()
398
    {
399
        try {
400
            newdocid = generateDocid();
401
            String identifier = newdocid + ".1";
402
            m.login(username, password);
403
            File testFile = new File(onlinetestdatafile);
404
            String response = m.upload(identifier, "onlineDataFile1",
405
                                       new FileInputStream(testFile),
406
                                       (int) testFile.length());
407

    
408
            assertTrue(response.indexOf("<success>") != -1);
409
            assertTrue(response.indexOf(identifier) != -1);
410
            identifier = newdocid + ".2";
411
            response = m.upload(identifier, "onlineDataFile1",
412
                    new FileInputStream(testFile),
413
                    (int) testFile.length());
414

    
415
           assertTrue(response.indexOf("<success>") != -1);
416
           assertTrue(response.indexOf(identifier) != -1);
417
            //System.err.println(response);
418

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

    
434
    /**
435
     * Test the invalidUpdate() function. A user try to update a document
436
     * which it doesn't have permission
437
     */
438
    public void invalidUpdate()
439
    {
440
        try {
441
        	String docid = readIdFromFile(DOCID);
442
            String identifier = docid + ".2";
443
            m.login(anotheruser, anotherpassword);
444
            String response = m.update(identifier,
445
                    new StringReader(testdocument), null);
446
            assertTrue(response.indexOf("<success>") == -1);
447

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

    
461
    /**
462
     * Test the update() function with a known document
463
     */
464
    public void update()
465
    {
466
        try {
467
        	String docid = readIdFromFile(DOCID);
468
            String identifier = docid + ".2";
469
            m.login(username, password);
470
            String response = m.update(identifier,
471
                    new StringReader(testdocument), null);
472
            assertTrue(response.indexOf("<success>") != -1);
473
            assertTrue(response.indexOf(identifier) != -1);
474
            //System.err.println(response);
475

    
476
        } catch (MetacatAuthException mae) {
477
            fail("Authorization failed:\n" + mae.getMessage());
478
        } catch (MetacatInaccessibleException mie) {
479
            fail("Metacat Inaccessible:\n" + mie.getMessage());
480
        } catch (InsufficientKarmaException ike) {
481
            fail("Insufficient karma:\n" + ike.getMessage());
482
        } catch (MetacatException me) {
483
            fail("Metacat Error:\n" + me.getMessage());
484
        } catch (Exception e) {
485
            fail("General exception:\n" + e.getMessage());
486
        }
487
    }
488

    
489
    /**
490
     * A user try delete a document which it doesn't have permission
491
     */
492
    public void invalidDelete()
493
    {
494
        try {
495
            String identifier = newdocid + ".2";
496
            m.login(anotheruser, anotherpassword);
497
            String response = m.delete(identifier);
498
            assertTrue(response.indexOf("<success>") == -1);
499
            //System.err.println(response);
500

    
501
        } catch (MetacatAuthException mae) {
502
            fail("Authorization failed:\n" + mae.getMessage());
503
        } catch (MetacatInaccessibleException mie) {
504
            fail("Metacat Inaccessible:\n" + mie.getMessage());
505
        } catch (InsufficientKarmaException ike) {
506
            assertTrue(1 == 1);
507
        } catch (MetacatException me) {
508
            assertTrue(1 == 1);
509
        } catch (Exception e) {
510
            fail("General exception:\n" + e.getMessage());
511
        }
512
    }
513

    
514
    /**
515
     * Test the delete() function with a known document
516
     */
517
    public void delete()
518
    {
519
        try {
520
        	Thread.sleep(10000);
521
        	String docid = readIdFromFile(DOCID);
522
            String identifier = docid + ".2";
523
            m.login(username, password);
524
            String response = m.delete(identifier);
525
            assertTrue(response.indexOf("<success>") != -1);
526
            // delete the docid persistence file.
527
            deleteFile(DOCID);
528
            deleteFile(DATAID);
529
            //System.err.println(response);
530

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

    
544
    /**
545
     * Test the to connect a wrong metacat url. Create a new metacat with a
546
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
547
     * exception, this is right.
548
     */
549
    public void inaccessibleMetacat()
550
    {
551
        Metacat mWrong = null;
552
        try {
553
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
554
        } catch (MetacatInaccessibleException mie) {
555
            fail("Metacat Inaccessible:\n" + mie.getMessage());
556
        }
557

    
558
        try {
559
            mWrong.login(username, password);
560
        } catch (MetacatInaccessibleException mie) {
561
            assertTrue(1 == 1);
562
        } catch (MetacatAuthException mae) {
563
            fail("Authorization failed:\n" + mae.getMessage());
564
        }
565
    }
566

    
567
    /**
568
     * Try to perform an action that requires a session to be valid without
569
     * having logged in first by setting the sessionId from a previous
570
     * session.  Then insert a document.
571
     */
572
    public void reuseSession()
573
    {
574
        String oldSessionId = "";
575
        try {
576
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
577
            String response = mtemp.login(username, password);
578
            oldSessionId = mtemp.getSessionId();
579
            //System.err.println("SessionId (mtemp): " + oldSessionId);
580
        } catch (MetacatAuthException mae) {
581
            fail("Authorization failed:\n" + mae.getMessage());
582
        } catch (MetacatInaccessibleException mie) {
583
            System.err.println("Metacat is: " + metacatUrl);
584
            fail("Metacat connection failed." + mie.getMessage());
585
        }
586

    
587
        try {
588
            String identifier = generateDocid() + ".1";
589
            Metacat m2 = null;
590
            try {
591
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
592
                m2.logout();
593
            } catch (MetacatInaccessibleException mie) {
594
                System.err.println("Metacat is: " + metacatUrl);
595
                fail("Metacat connection failed." + mie.getMessage());
596
            }
597
            System.err.println("SessionId (m2): " + m2.getSessionId());
598
            m2.setSessionId(oldSessionId);
599
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
600
            String response = m2.insert(identifier,
601
                    new StringReader(testdocument), null);
602
            System.err.println("Reuse Insert response: " + response);
603
            assertTrue(response.indexOf("<success>") != -1);
604
        } catch (MetacatInaccessibleException mie) {
605
            fail("Metacat Inaccessible:\n" + mie.getMessage());
606
        } catch (InsufficientKarmaException ike) {
607
            fail("Insufficient karma:\n" + ike.getMessage());
608
        } catch (MetacatException me) {
609
            fail("Metacat Error:\n" + me.getMessage());
610
        } catch (Exception e) {
611
            fail("General exception:\n" + e.getMessage());
612
        }
613
    }
614

    
615
    /**
616
     * Try to perform an action that requires a session to be valid without
617
     * having logged in first, but use an invalid session identifier.
618
     * Then insert a document, which should fail.
619
     */
620
    public void reuseInvalidSession()
621
    {
622
        System.err.println("Starting resuseInvalidSession test...");
623
        String oldSessionId = "foobar";
624
        try {
625
            String identifier = generateDocid() + ".1";
626
            Metacat m3 = null;
627
            try {
628
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
629
                m3.logout();
630
            } catch (MetacatInaccessibleException mie) {
631
                System.err.println("Metacat is: " + metacatUrl);
632
                fail("Metacat connection failed." + mie.getMessage());
633
            }
634
            System.err.println("SessionId (m3): " + m3.getSessionId());
635
            m3.setSessionId(oldSessionId);
636
            System.err.println("SessionId (m3 after set): " + m3.getSessionId());
637
            System.err.println("Performing resuseInvalidSession insert: " +
638
                    identifier);
639
            String response = m3.insert(identifier,
640
                    new StringReader(testdocument), null);
641
            System.err.println("ReuseInvalid Insert response: " + response);
642
            assertTrue(response.indexOf("<success>") == -1);
643
        } catch (MetacatInaccessibleException mie) {
644
            fail("Metacat Inaccessible:\n" + mie.getMessage());
645
        } catch (InsufficientKarmaException ike) {
646
            fail("Insufficient karma:\n" + ike.getMessage());
647
        } catch (MetacatException me) {
648
            if(me.getMessage().
649
               indexOf("Permission denied for user public inser") == -1){
650
                fail("Metacat Error:\n" + me.getMessage());
651
            }
652
        } catch (Exception e) {
653
            fail("General exception:\n" + e.getMessage());
654
        }
655
    }
656
    
657
   /**
658
    * Get the most recent document id for a given scope and be sure
659
    * that it matches the one we last inserted. Assumes this test is run
660
    * immediately following a successful insert() test.
661
    */
662
   public void getLastDocid()
663
   {
664
       try {
665
           Metacat m3 = null;
666
           try {
667
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
668
           } catch (MetacatInaccessibleException mie) {
669
               System.err.println("Metacat is: " + metacatUrl);
670
               fail("Metacat connection failed." + mie.getMessage());
671
           }
672
           String lastId = m3.getLastDocid(prefix);
673
           System.err.println("Last Id: " + lastId);
674
           //get docid from file
675
           String docid = readIdFromFile(DOCID);
676
           assertTrue(lastId.equals(docid + ".1"));
677
       } catch (MetacatException me) {
678
           fail("Metacat Error:\n" + me.getMessage());
679
       } catch (Exception e) {
680
           fail("General exception:\n" + e.getMessage());
681
       }
682
   }
683

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

    
781
	int time = 0; 
782
	
783
	docid.append(calendar.get(Calendar.YEAR));
784
	
785
	time = calendar.get(Calendar.DAY_OF_YEAR);
786
	if(time < 10){
787
		docid.append("0");
788
		docid.append("0");
789
		docid.append(time);
790
	} else if(time < 100) {
791
		docid.append("0");
792
		docid.append(time);
793
	} else {
794
		docid.append(time);
795
	}
796
	
797
	time = calendar.get(Calendar.HOUR_OF_DAY);
798
	if(time < 10){
799
		docid.append("0");
800
		docid.append(time);
801
	} else {
802
		docid.append(time);
803
	}
804
	
805
	time = calendar.get(Calendar.MINUTE);
806
	if(time < 10){
807
		docid.append("0");
808
		docid.append(time);
809
	} else {
810
		docid.append(time);
811
	}
812
	
813
	time = calendar.get(Calendar.SECOND);
814
	if(time < 10){
815
		docid.append("0");
816
		docid.append(time);
817
	} else {
818
		docid.append(time);
819
	}
820
    
821
	 //sometimes this number is not unique, so we append a random number
822
	int random = (new Double(Math.random()*100)).intValue();
823
	docid.append(random);
824
	
825
	return docid.toString();
826
    }
827
    
828
    /*
829
     * Write id to a file for persistance
830
     */
831
    private void writeIdToFile(String fileName, String id) throws Exception
832
    {
833
    	File file = new File(fileName);
834
    	StringReader reader = new StringReader(id);
835
    	FileWriter writer = new FileWriter(file);
836
    	char [] buffer = new char[1024];
837
    	int c = reader.read(buffer);
838
    	while (c != -1)
839
    	{
840
    		writer.write(buffer, 0, c);
841
    		c = reader.read(buffer);
842
    	}
843
    	writer.close();
844
    	reader.close();
845
    }
846
    
847
    /*
848
     * Read id from a given file
849
     */
850
    private String readIdFromFile(String fileName) throws Exception
851
    {
852
    	File file = new File(fileName);
853
    	FileReader reader = new FileReader(file);
854
    	StringWriter writer = new StringWriter();
855
    	char [] buffer = new char[1024];
856
    	int c = reader.read(buffer);
857
    	while (c != -1)
858
    	{
859
    		writer.write(buffer, 0, c);
860
    		c = reader.read(buffer);
861
    	}
862
    	reader.close();
863
    	return writer.toString();
864
    }
865
    
866
    /*
867
     * Delete the given file
868
     */
869
    private void deleteFile(String fileName) throws Exception
870
    {
871
    	File file = new File(fileName);
872
    	file.delete();
873
    }
874
}
    (1-1/1)