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-09-11 17:35:02 -0700 (Tue, 11 Sep 2007) $'
9
 * '$Revision: 3425 $'
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("invalidUpdate"));
140
      suite.addTest(new MetacatClientTest("update"));
141
      suite.addTest(new MetacatClientTest("invalidDelete"));
142
      suite.addTest(new MetacatClientTest("delete"));
143
      suite.addTest(new MetacatClientTest("inaccessibleMetacat"));
144
      suite.addTest(new MetacatClientTest("reuseSession"));
145
      suite.addTest(new MetacatClientTest("reuseInvalidSession"));
146
      //suite.addTest(new MetacatClientTest("insertSpatialDocs"));
147
      return suite;
148
  }
149

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

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

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

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

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

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

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

    
279
    /**
280
     * Test the query() function with a known document
281
     */
282
    public void query()
283
    {
284
        try {
285
            m.login(username,password);
286
            FileReader fr = new FileReader(queryFile);
287
            Reader r = m.query(fr);
288
            //System.err.println("Starting query...");
289
            String result = IOUtil.getAsString(r, true);
290
            //System.err.println("Query result:\n" + result);
291
            String docid = readIdFromFile(DOCID);
292
            assertTrue(result.indexOf(docid+".1")!=-1);
293
        } catch (MetacatAuthException mae) {
294
            fail("Authorization failed:\n" + mae.getMessage());
295
        } catch (MetacatInaccessibleException mie) {
296
            fail("Metacat Inaccessible:\n" + mie.getMessage());
297
        } catch (Exception e) {
298
            fail("General exception:\n" + e.getMessage());
299
        }
300
    }
301

    
302
    /**
303
     * Test the insert() function with a known document
304
     */
305
    public void insert()
306
    {
307
        try {
308
            String identifier = newdocid + ".1";
309
            //write newdocid into file for persistance
310
            writeIdToFile(DOCID, newdocid);
311
            m.login(username, password);
312
            String response = m.insert(identifier,
313
                    new StringReader(testdocument), null);
314
            assertTrue(response.indexOf("<success>") != -1);
315
            assertTrue(response.indexOf(identifier) != -1);
316
            //System.err.println(response);
317

    
318
        } catch (MetacatAuthException mae) {
319
            fail("Authorization failed:\n" + mae.getMessage());
320
        } catch (MetacatInaccessibleException mie) {
321
            fail("Metacat Inaccessible:\n" + mie.getMessage());
322
        } catch (InsufficientKarmaException ike) {
323
            assertTrue(1 == 1);
324
            fail("Insufficient karma:\n" + ike.getMessage());
325
        } catch (MetacatException me) {
326
            fail("Metacat Error:\n" + me.getMessage());
327
        } catch (Exception e) {
328
            fail("General exception:\n" + e.getMessage());
329
        }
330
    }
331

    
332
    /**
333
     * Test the upload() function with a known document
334
     */
335
    public void upload()
336
    {
337
        try {
338
            newdocid = generateDocid();
339
            String identifier = newdocid + ".1";
340
            writeIdToFile(DATAID, newdocid);
341
            m.login(username, password);
342
            String response = m.upload(identifier,
343
                                     new File(onlinetestdatafile));
344
            assertTrue(response.indexOf("<success>") != -1);
345
            assertTrue(response.indexOf(identifier) != -1);
346
            identifier = newdocid +".2";
347
            response = m.upload(identifier,
348
                    new File(onlinetestdatafile));
349
            assertTrue(response.indexOf("<success>") != -1);
350
            assertTrue(response.indexOf(identifier) != -1);
351
            //System.err.println(response);
352

    
353
        } catch (MetacatAuthException mae) {
354
            fail("Authorization failed:\n" + mae.getMessage());
355
        } catch (MetacatInaccessibleException mie) {
356
          mie.printStackTrace();
357
            fail("Metacat Inaccessible:\n" + mie.getMessage());
358
        } catch (InsufficientKarmaException ike) {
359
            assertTrue(1 == 1);
360
            fail("Insufficient karma:\n" + ike.getMessage());
361
        } catch (MetacatException me) {
362
            fail("Metacat Error:\n" + me.getMessage());
363
        } catch (Exception e) {
364
            fail("General exception:\n" + e.getMessage());
365
        }
366
    }
367

    
368
    /**
369
     * Test the upload() function by passing an InputStream
370
     */
371
    public void upload_stream()
372
    {
373
        try {
374
            newdocid = generateDocid();
375
            String identifier = newdocid + ".1";
376
            m.login(username, password);
377
            File testFile = new File(onlinetestdatafile);
378
            String response = m.upload(identifier, "onlineDataFile1",
379
                                       new FileInputStream(testFile),
380
                                       (int) testFile.length());
381

    
382
            assertTrue(response.indexOf("<success>") != -1);
383
            assertTrue(response.indexOf(identifier) != -1);
384
            identifier = newdocid + ".2";
385
            response = m.upload(identifier, "onlineDataFile1",
386
                    new FileInputStream(testFile),
387
                    (int) testFile.length());
388

    
389
           assertTrue(response.indexOf("<success>") != -1);
390
           assertTrue(response.indexOf(identifier) != -1);
391
            //System.err.println(response);
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
     * Test the invalidUpdate() function. A user try to update a document
410
     * which it doesn't have permission
411
     */
412
    public void invalidUpdate()
413
    {
414
        try {
415
        	String docid = readIdFromFile(DOCID);
416
            String identifier = docid + ".2";
417
            m.login(anotheruser, anotherpassword);
418
            String response = m.update(identifier,
419
                    new StringReader(testdocument), null);
420
            assertTrue(response.indexOf("<success>") == -1);
421

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

    
435
    /**
436
     * Test the update() function with a known document
437
     */
438
    public void update()
439
    {
440
        try {
441
        	String docid = readIdFromFile(DOCID);
442
            String identifier = docid + ".2";
443
            m.login(username, password);
444
            String response = m.update(identifier,
445
                    new StringReader(testdocument), null);
446
            assertTrue(response.indexOf("<success>") != -1);
447
            assertTrue(response.indexOf(identifier) != -1);
448
            //System.err.println(response);
449

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

    
463
    /**
464
     * A user try delete a document which it doesn't have permission
465
     */
466
    public void invalidDelete()
467
    {
468
        try {
469
            String identifier = newdocid + ".2";
470
            m.login(anotheruser, anotherpassword);
471
            String response = m.delete(identifier);
472
            assertTrue(response.indexOf("<success>") == -1);
473
            //System.err.println(response);
474

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

    
488
    /**
489
     * Test the delete() function with a known document
490
     */
491
    public void delete()
492
    {
493
        try {
494
        	Thread.sleep(10000);
495
        	String docid = readIdFromFile(DOCID);
496
            String identifier = docid + ".2";
497
            m.login(username, password);
498
            String response = m.delete(identifier);
499
            assertTrue(response.indexOf("<success>") != -1);
500
            // delete the docid persistence file.
501
            deleteFile(DOCID);
502
            deleteFile(DATAID);
503
            //System.err.println(response);
504

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

    
518
    /**
519
     * Test the to connect a wrong metacat url. Create a new metacat with a
520
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
521
     * exception, this is right.
522
     */
523
    public void inaccessibleMetacat()
524
    {
525
        Metacat mWrong = null;
526
        try {
527
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
528
        } catch (MetacatInaccessibleException mie) {
529
            fail("Metacat Inaccessible:\n" + mie.getMessage());
530
        }
531

    
532
        try {
533
            mWrong.login(username, password);
534
        } catch (MetacatInaccessibleException mie) {
535
            assertTrue(1 == 1);
536
        } catch (MetacatAuthException mae) {
537
            fail("Authorization failed:\n" + mae.getMessage());
538
        }
539
    }
540

    
541
    /**
542
     * Try to perform an action that requires a session to be valid without
543
     * having logged in first by setting the sessionId from a previous
544
     * session.  Then insert a document.
545
     */
546
    public void reuseSession()
547
    {
548
        String oldSessionId = "";
549
        try {
550
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
551
            String response = mtemp.login(username, password);
552
            oldSessionId = mtemp.getSessionId();
553
            //System.err.println("SessionId (mtemp): " + oldSessionId);
554
        } catch (MetacatAuthException mae) {
555
            fail("Authorization failed:\n" + mae.getMessage());
556
        } catch (MetacatInaccessibleException mie) {
557
            System.err.println("Metacat is: " + metacatUrl);
558
            fail("Metacat connection failed." + mie.getMessage());
559
        }
560

    
561
        try {
562
            String identifier = generateDocid() + ".1";
563
            Metacat m2 = null;
564
            try {
565
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
566
            } catch (MetacatInaccessibleException mie) {
567
                System.err.println("Metacat is: " + metacatUrl);
568
                fail("Metacat connection failed." + mie.getMessage());
569
            }
570
            System.err.println("SessionId (m2): " + m2.getSessionId());
571
            m2.setSessionId(oldSessionId);
572
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
573
            String response = m2.insert(identifier,
574
                    new StringReader(testdocument), null);
575
            System.err.println("Reuse Insert response: " + response);
576
            assertTrue(response.indexOf("<success>") != -1);
577
        } catch (MetacatInaccessibleException mie) {
578
            fail("Metacat Inaccessible:\n" + mie.getMessage());
579
        } catch (InsufficientKarmaException ike) {
580
            fail("Insufficient karma:\n" + ike.getMessage());
581
        } catch (MetacatException me) {
582
            fail("Metacat Error:\n" + me.getMessage());
583
        } catch (Exception e) {
584
            fail("General exception:\n" + e.getMessage());
585
        }
586
    }
587

    
588
    /**
589
     * Try to perform an action that requires a session to be valid without
590
     * having logged in first, but use an invalid session identifier.
591
     * Then insert a document, which should fail.
592
     */
593
    public void reuseInvalidSession()
594
    {
595
        System.err.println("Starting resuseInvalidSession test...");
596
        String oldSessionId = "foobar";
597
        try {
598
            String identifier = generateDocid() + ".1";
599
            Metacat m3 = null;
600
            try {
601
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
602
            } catch (MetacatInaccessibleException mie) {
603
                System.err.println("Metacat is: " + metacatUrl);
604
                fail("Metacat connection failed." + mie.getMessage());
605
            }
606
            System.err.println("SessionId (m3): " + m3.getSessionId());
607
            m3.setSessionId(oldSessionId);
608
            System.err.println("SessionId (m3 after set): " + m3.getSessionId());
609
            System.err.println("Performing resuseInvalidSession insert: " +
610
                    identifier);
611
            String response = m3.insert(identifier,
612
                    new StringReader(testdocument), null);
613
            System.err.println("ReuseInvalid Insert response: " + response);
614
            assertTrue(response.indexOf("<success>") == -1);
615
        } catch (MetacatInaccessibleException mie) {
616
            fail("Metacat Inaccessible:\n" + mie.getMessage());
617
        } catch (InsufficientKarmaException ike) {
618
            fail("Insufficient karma:\n" + ike.getMessage());
619
        } catch (MetacatException me) {
620
            if(me.getMessage().
621
               indexOf("Permission denied for user public inser") == -1){
622
                fail("Metacat Error:\n" + me.getMessage());
623
            }
624
        } catch (Exception e) {
625
            fail("General exception:\n" + e.getMessage());
626
        }
627
    }
628
    
629
   /**
630
    * Get the most recent document id for a given scope and be sure
631
    * that it matches the one we last inserted. Assumes this test is run
632
    * immediately following a successful insert() test.
633
    */
634
   public void getLastDocid()
635
   {
636
       try {
637
           Metacat m3 = null;
638
           try {
639
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
640
           } catch (MetacatInaccessibleException mie) {
641
               System.err.println("Metacat is: " + metacatUrl);
642
               fail("Metacat connection failed." + mie.getMessage());
643
           }
644
           String lastId = m3.getLastDocid(prefix);
645
           System.err.println("Last Id: " + lastId);
646
           //get docid from file
647
           String docid = readIdFromFile(DOCID);
648
           assertTrue(lastId.equals(docid + ".1"));
649
       } catch (MetacatException me) {
650
           fail("Metacat Error:\n" + me.getMessage());
651
       } catch (Exception e) {
652
           fail("General exception:\n" + e.getMessage());
653
       }
654
   }
655

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

    
753
	int time = 0; 
754
	
755
	docid.append(calendar.get(Calendar.YEAR));
756
	
757
	time = calendar.get(Calendar.DAY_OF_YEAR);
758
	if(time < 10){
759
		docid.append("0");
760
		docid.append("0");
761
		docid.append(time);
762
	} else if(time < 100) {
763
		docid.append("0");
764
		docid.append(time);
765
	} else {
766
		docid.append(time);
767
	}
768
	
769
	time = calendar.get(Calendar.HOUR_OF_DAY);
770
	if(time < 10){
771
		docid.append("0");
772
		docid.append(time);
773
	} else {
774
		docid.append(time);
775
	}
776
	
777
	time = calendar.get(Calendar.MINUTE);
778
	if(time < 10){
779
		docid.append("0");
780
		docid.append(time);
781
	} else {
782
		docid.append(time);
783
	}
784
	
785
	time = calendar.get(Calendar.SECOND);
786
	if(time < 10){
787
		docid.append("0");
788
		docid.append(time);
789
	} else {
790
		docid.append(time);
791
	}
792
    
793
	 //sometimes this number is not unique, so we append a random number
794
	int random = (new Double(Math.random()*100)).intValue();
795
	docid.append(random);
796
	
797
	return docid.toString();
798
    }
799
    
800
    /*
801
     * Write id to a file for persistance
802
     */
803
    private void writeIdToFile(String fileName, String id) throws Exception
804
    {
805
    	File file = new File(fileName);
806
    	StringReader reader = new StringReader(id);
807
    	FileWriter writer = new FileWriter(file);
808
    	char [] buffer = new char[1024];
809
    	int c = reader.read(buffer);
810
    	while (c != -1)
811
    	{
812
    		writer.write(buffer, 0, c);
813
    		c = reader.read(buffer);
814
    	}
815
    	writer.close();
816
    	reader.close();
817
    }
818
    
819
    /*
820
     * Read id from a given file
821
     */
822
    private String readIdFromFile(String fileName) throws Exception
823
    {
824
    	File file = new File(fileName);
825
    	FileReader reader = new FileReader(file);
826
    	StringWriter writer = new StringWriter();
827
    	char [] buffer = new char[1024];
828
    	int c = reader.read(buffer);
829
    	while (c != -1)
830
    	{
831
    		writer.write(buffer, 0, c);
832
    		c = reader.read(buffer);
833
    	}
834
    	reader.close();
835
    	return writer.toString();
836
    }
837
    
838
    /*
839
     * Delete the given file
840
     */
841
    private void deleteFile(String fileName) throws Exception
842
    {
843
    	File file = new File(fileName);
844
    	file.delete();
845
    }
846
}
    (1-1/1)