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: 2008-04-02 15:21:40 -0700 (Wed, 02 Apr 2008) $'
9
 * '$Revision: 3779 $'
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 data file.
360
     * 1. Insert version 1 successfully.
361
     * 2. Update version 2 successfully
362
     * 3. Update version 2 again and should be failed.
363
     */
364
    public void upload()
365
    {
366
        try {
367
            newdocid = generateDocid();
368
            String identifier = newdocid + ".1";
369
            writeIdToFile(DATAID, newdocid);
370
            m.login(username, password);
371
            String response = m.upload(identifier,
372
                                     new File(onlinetestdatafile));
373
            assertTrue(response.indexOf("<success>") != -1);
374
            assertTrue(response.indexOf(identifier) != -1);
375
            identifier = newdocid +".2";
376
            response = m.upload(identifier,
377
                    new File(onlinetestdatafile));
378
            assertTrue(response.indexOf("<success>") != -1);
379
            assertTrue(response.indexOf(identifier) != -1);
380
            //System.err.println(response);
381
            //upload the same identifier again. it should return an error
382
            try
383
            {
384
                response = m.upload(identifier,
385
                      new File(onlinetestdatafile));
386
                fail("Metacat shouldn't successfully upload the same identifier twice "+response);
387
            }
388
            catch(Exception ee)
389
            {
390
                assertTrue(ee.getMessage().indexOf("<error>") != -1);
391
            }
392

    
393
        } catch (MetacatAuthException mae) {
394
            fail("Authorization failed:\n" + mae.getMessage());
395
        } catch (MetacatInaccessibleException mie) {
396
          mie.printStackTrace();
397
            fail("Metacat Inaccessible:\n" + mie.getMessage());
398
        } catch (InsufficientKarmaException ike) {
399
            assertTrue(1 == 1);
400
            fail("Insufficient karma:\n" + ike.getMessage());
401
        } catch (MetacatException me) {
402
            fail("Metacat Error:\n" + me.getMessage());
403
        } catch (Exception e) {
404
            fail("General exception:\n" + e.getMessage());
405
        }
406
    }
407
    
408

    
409

    
410
    /**
411
     * Test the upload() function by passing an InputStream
412
     */
413
    public void upload_stream()
414
    {
415
        try {
416
            newdocid = generateDocid();
417
            String identifier = newdocid + ".1";
418
            m.login(username, password);
419
            File testFile = new File(onlinetestdatafile);
420
            String response = m.upload(identifier, "onlineDataFile1",
421
                                       new FileInputStream(testFile),
422
                                       (int) testFile.length());
423

    
424
            assertTrue(response.indexOf("<success>") != -1);
425
            assertTrue(response.indexOf(identifier) != -1);
426
            identifier = newdocid + ".2";
427
            response = m.upload(identifier, "onlineDataFile1",
428
                    new FileInputStream(testFile),
429
                    (int) testFile.length());
430

    
431
           assertTrue(response.indexOf("<success>") != -1);
432
           assertTrue(response.indexOf(identifier) != -1);
433
            //System.err.println(response);
434

    
435
        } catch (MetacatAuthException mae) {
436
            fail("Authorization failed:\n" + mae.getMessage());
437
        } catch (MetacatInaccessibleException mie) {
438
          mie.printStackTrace();
439
            fail("Metacat Inaccessible:\n" + mie.getMessage());
440
        } catch (InsufficientKarmaException ike) {
441
            assertTrue(1 == 1);
442
            fail("Insufficient karma:\n" + ike.getMessage());
443
        } catch (MetacatException me) {
444
            fail("Metacat Error:\n" + me.getMessage());
445
        } catch (Exception e) {
446
            fail("General exception:\n" + e.getMessage());
447
        }
448
    }
449

    
450
    /**
451
     * Test the invalidUpdate() function. A user try to update a document
452
     * which it doesn't have permission
453
     */
454
    public void invalidUpdate()
455
    {
456
        try {
457
        	String docid = readIdFromFile(DOCID);
458
            String identifier = docid + ".2";
459
            m.login(anotheruser, anotherpassword);
460
            String response = m.update(identifier,
461
                    new StringReader(testdocument), null);
462
            assertTrue(response.indexOf("<success>") == -1);
463

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

    
477
    /**
478
     * Test the update() function with a known document
479
     */
480
    public void update()
481
    {
482
        try {
483
        	String docid = readIdFromFile(DOCID);
484
            String identifier = docid + ".2";
485
            m.login(username, password);
486
            String response = m.update(identifier,
487
                    new StringReader(testdocument), null);
488
            assertTrue(response.indexOf("<success>") != -1);
489
            assertTrue(response.indexOf(identifier) != -1);
490
            //System.err.println(response);
491

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

    
505
    /**
506
     * A user try delete a document which it doesn't have permission
507
     */
508
    public void invalidDelete()
509
    {
510
        try {
511
            String identifier = newdocid + ".2";
512
            m.login(anotheruser, anotherpassword);
513
            String response = m.delete(identifier);
514
            assertTrue(response.indexOf("<success>") == -1);
515
            //System.err.println(response);
516

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

    
530
    /**
531
     * Test the delete() function with a known document
532
     */
533
    public void delete()
534
    {
535
        try {
536
        	Thread.sleep(10000);
537
        	String docid = readIdFromFile(DOCID);
538
            String identifier = docid + ".2";
539
            m.login(username, password);
540
            String response = m.delete(identifier);
541
            assertTrue(response.indexOf("<success>") != -1);
542
            // delete the docid persistence file.
543
            deleteFile(DOCID);
544
            deleteFile(DATAID);
545
            //System.err.println(response);
546

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

    
560
    /**
561
     * Test the to connect a wrong metacat url. Create a new metacat with a
562
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
563
     * exception, this is right.
564
     */
565
    public void inaccessibleMetacat()
566
    {
567
        Metacat mWrong = null;
568
        try {
569
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
570
        } catch (MetacatInaccessibleException mie) {
571
            fail("Metacat Inaccessible:\n" + mie.getMessage());
572
        }
573

    
574
        try {
575
            mWrong.login(username, password);
576
        } catch (MetacatInaccessibleException mie) {
577
            assertTrue(1 == 1);
578
        } catch (MetacatAuthException mae) {
579
            fail("Authorization failed:\n" + mae.getMessage());
580
        }
581
    }
582

    
583
    /**
584
     * Try to perform an action that requires a session to be valid without
585
     * having logged in first by setting the sessionId from a previous
586
     * session.  Then insert a document.
587
     */
588
    public void reuseSession()
589
    {
590
        String oldSessionId = "";
591
        try {
592
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
593
            String response = mtemp.login(username, password);
594
            oldSessionId = mtemp.getSessionId();
595
            //System.err.println("SessionId (mtemp): " + oldSessionId);
596
        } catch (MetacatAuthException mae) {
597
            fail("Authorization failed:\n" + mae.getMessage());
598
        } catch (MetacatInaccessibleException mie) {
599
            System.err.println("Metacat is: " + metacatUrl);
600
            fail("Metacat connection failed." + mie.getMessage());
601
        }
602

    
603
        try {
604
            String identifier = generateDocid() + ".1";
605
            Metacat m2 = null;
606
            try {
607
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
608
                m2.logout();
609
            } catch (MetacatInaccessibleException mie) {
610
                System.err.println("Metacat is: " + metacatUrl);
611
                fail("Metacat connection failed." + mie.getMessage());
612
            }
613
            System.err.println("SessionId (m2): " + m2.getSessionId());
614
            m2.setSessionId(oldSessionId);
615
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
616
            String response = m2.insert(identifier,
617
                    new StringReader(testdocument), null);
618
            System.err.println("Reuse Insert response: " + response);
619
            assertTrue(response.indexOf("<success>") != -1);
620
        } catch (MetacatInaccessibleException mie) {
621
            fail("Metacat Inaccessible:\n" + mie.getMessage());
622
        } catch (InsufficientKarmaException ike) {
623
            fail("Insufficient karma:\n" + ike.getMessage());
624
        } catch (MetacatException me) {
625
            fail("Metacat Error:\n" + me.getMessage());
626
        } catch (Exception e) {
627
            fail("General exception:\n" + e.getMessage());
628
        }
629
    }
630

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

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

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