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-04-02 16:28:31 -0700 (Wed, 02 Apr 2008) $'
9
 * '$Revision: 3780 $'
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.MetaCatUtil;
43
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
44
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
45
import edu.ucsb.nceas.metacat.client.Metacat;
46
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
47
import edu.ucsb.nceas.metacat.client.MetacatException;
48
import edu.ucsb.nceas.metacat.client.MetacatFactory;
49
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
50
import edu.ucsb.nceas.utilities.IOUtil;
51
import junit.framework.Test;
52
import junit.framework.TestCase;
53
import junit.framework.TestSuite;
54
import java.io.FileInputStream;
55

    
56
import org.apache.log4j.Logger;
57

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
410

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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