Project

General

Profile

1 1783 jones
/**
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$'
8
 *     '$Date$'
9
 * '$Revision$'
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 2242 sgarg
import java.io.File;
29 1784 jones
import java.io.FileReader;
30 3212 tao
import java.io.FileWriter;
31 1784 jones
import java.io.IOException;
32
import java.io.Reader;
33 1789 jones
import java.io.StringReader;
34 3212 tao
import java.io.StringWriter;
35 1791 jones
import java.util.Calendar;
36 2242 sgarg
import java.util.Date;
37 1791 jones
import java.util.GregorianCalendar;
38
import java.util.SimpleTimeZone;
39
import java.util.TimeZone;
40 1784 jones
41 3172 tao
import edu.ucsb.nceas.metacat.DocumentImpl;
42
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
43 2242 sgarg
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 1783 jones
import junit.framework.Test;
51
import junit.framework.TestCase;
52
import junit.framework.TestSuite;
53 2265 sgarg
import java.io.FileInputStream;
54 1783 jones
55 3172 tao
import org.apache.log4j.Logger;
56
57 1783 jones
/**
58
 * A JUnit test for testing Step class processing
59
 */
60
public class MetacatClientTest extends TestCase
61
{
62 1828 jones
    private String metacatUrl = "@systemidserver@@servlet-path@";
63 1800 tao
    private String wrongMetacatUrl=
64
                    "http://somepalce.somewhere.com/some/servlet/metacat";
65 1783 jones
    private String username = "@mcuser@";
66
    private String password = "@mcpassword@";
67 1800 tao
    private String anotheruser = "@mcanotheruser@";
68
    private String anotherpassword = "@mcanotherpassword@";
69 1783 jones
    private String failpass = "uidfnkj43987yfdn";
70 1791 jones
    private String prefix = "test";
71
    private String newdocid = null;
72 1784 jones
    private String testfile = "test/jones.204.22.xml";
73 2242 sgarg
    private String onlinetestdatafile = "test/onlineDataFile1";
74 1787 tao
    private String queryFile = "test/query.xml";
75 1784 jones
    private String testdocument = "";
76 1783 jones
    private Metacat m;
77 3172 tao
    private String spatialTestFile = "test/spatialEml.xml";
78
    private static final int TIME = 30;
79 3212 tao
    private static final String DOCID = "docid";
80
    private static final String DATAID = "dataid";
81 3172 tao
82 1783 jones
    /**
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 1791 jones
        newdocid = generateDocid();
91 1783 jones
    }
92
93
    /**
94
     * Establish a testing framework by initializing appropriate objects
95
     */
96
    public void setUp()
97
    {
98
        try {
99 1784 jones
            FileReader fr = new FileReader(testfile);
100 1788 jones
            testdocument = IOUtil.getAsString(fr, true);
101 1784 jones
        } catch (IOException ioe) {
102
            fail("Can't read test data to run the test: " + testfile);
103
        }
104
105
        try {
106 1828 jones
            System.err.println("Test Metacat: " + metacatUrl);
107 1783 jones
            m = MetacatFactory.createMetacatConnection(metacatUrl);
108
        } catch (MetacatInaccessibleException mie) {
109 1822 jones
            System.err.println("Metacat is: " + metacatUrl);
110 1783 jones
            fail("Metacat connection failed." + mie.getMessage());
111
        }
112
    }
113 2242 sgarg
114 1783 jones
    /**
115
     * Release any objects after tests are complete
116
     */
117
    public void tearDown()
118
    {
119
    }
120 2242 sgarg
121 1783 jones
    /**
122
     * Create a suite of tests to be run together
123
     */
124
    public static Test suite()
125
    {
126 2242 sgarg
      TestSuite suite = new TestSuite();
127 2265 sgarg
      suite.addTest(new MetacatClientTest("initialize"));
128 2987 sgarg
      suite.addTest(new MetacatClientTest("invalidLogin"));
129
      suite.addTest(new MetacatClientTest("logoutAndInvalidInsert"));
130 2265 sgarg
      suite.addTest(new MetacatClientTest("login"));
131
      suite.addTest(new MetacatClientTest("insert"));
132 2987 sgarg
      suite.addTest(new MetacatClientTest("getNewestDocRevision"));
133 2981 jones
      suite.addTest(new MetacatClientTest("getLastDocid"));
134 2987 sgarg
      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 3172 tao
      //suite.addTest(new MetacatClientTest("insertSpatialDocs"));
147 2265 sgarg
      return suite;
148
  }
149 2242 sgarg
150 1783 jones
    /**
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 2242 sgarg
159 1783 jones
    /**
160
     * Test the login() function with valid credentials
161
     */
162
    public void login()
163
    {
164
        // Try a valid login
165
        try {
166 1822 jones
            String response = m.login(username, password);
167 2981 jones
            //System.err.println("Login response: " + response);
168 1822 jones
            assertTrue(response != null);
169
            assertTrue(response.indexOf("<login>") != -1);
170
            String sessionId = m.getSessionId();
171 2981 jones
            //System.err.println("Session ID: " + m.getSessionId());
172 1825 jones
            assertTrue(sessionId != null);
173
            assertTrue(response.indexOf(m.getSessionId()) != -1);
174 1783 jones
        } 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 2242 sgarg
197 1800 tao
    /**
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 2242 sgarg
            String response = m.insert(identifier,
208 1800 tao
                    new StringReader(testdocument), null);
209 2981 jones
            //System.err.println("Response in logout: "+response);
210 1800 tao
            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 2265 sgarg
            if(me.getMessage().
219
              indexOf("Permission denied for user public inser") == -1){
220
               fail("Metacat Error:\n" + me.getMessage());
221
           }
222 1800 tao
        } catch (Exception e) {
223
            fail("General exception:\n" + e.getMessage());
224
        }
225
    }
226 1784 jones
227
    /**
228
     * Test the read() function with a known document
229
     */
230
    public void read()
231
    {
232
        try {
233
            m.login(username, password);
234 3212 tao
            String docid = readIdFromFile(DOCID);
235
            Reader r = m.read(docid+".1");
236 1788 jones
            String doc = IOUtil.getAsString(r, true);
237 1800 tao
            doc = doc +"\n";
238 2981 jones
            //System.err.println(doc);
239 1784 jones
            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 2242 sgarg
249 1787 tao
    /**
250 1800 tao
     * 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 3212 tao
            String docid = readIdFromFile(DOCID);
257
            Reader r = m.read(docid+".1");
258 1800 tao
            String doc = IOUtil.getAsString(r, true);
259
            assertTrue(doc.indexOf("<error>") != -1);
260 2981 jones
            //System.err.println(doc);
261 1800 tao
        } 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 3172 tao
        } catch (IOException ioe) {
270
            fail("IO exception:\n" + ioe.getMessage());
271
        } catch (DocumentNotFoundException ne) {
272
            fail("DocumentNotFound exception:\n" + ne.getMessage());
273
274 3212 tao
        } catch(Exception e) {
275
            fail("Exception:\n" + e.getMessage());
276 1800 tao
        }
277
    }
278 2242 sgarg
279 1800 tao
    /**
280 1787 tao
     * Test the query() function with a known document
281
     */
282
    public void query()
283
    {
284
        try {
285 1828 jones
            m.login(username,password);
286 1787 tao
            FileReader fr = new FileReader(queryFile);
287
            Reader r = m.query(fr);
288 2981 jones
            //System.err.println("Starting query...");
289 1788 jones
            String result = IOUtil.getAsString(r, true);
290 2981 jones
            //System.err.println("Query result:\n" + result);
291 3212 tao
            String docid = readIdFromFile(DOCID);
292
            assertTrue(result.indexOf(docid+".1")!=-1);
293 1828 jones
        } catch (MetacatAuthException mae) {
294
            fail("Authorization failed:\n" + mae.getMessage());
295 1787 tao
        } catch (MetacatInaccessibleException mie) {
296
            fail("Metacat Inaccessible:\n" + mie.getMessage());
297
        } catch (Exception e) {
298
            fail("General exception:\n" + e.getMessage());
299
        }
300
    }
301 1789 jones
302
    /**
303
     * Test the insert() function with a known document
304
     */
305
    public void insert()
306
    {
307
        try {
308 1791 jones
            String identifier = newdocid + ".1";
309 3212 tao
            //write newdocid into file for persistance
310
            writeIdToFile(DOCID, newdocid);
311 1789 jones
            m.login(username, password);
312 2242 sgarg
            String response = m.insert(identifier,
313 1789 jones
                    new StringReader(testdocument), null);
314
            assertTrue(response.indexOf("<success>") != -1);
315 1791 jones
            assertTrue(response.indexOf(identifier) != -1);
316 2981 jones
            //System.err.println(response);
317 1789 jones
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 1800 tao
            assertTrue(1 == 1);
324 1789 jones
            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 1791 jones
332
    /**
333 2242 sgarg
     * 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 3212 tao
            writeIdToFile(DATAID, newdocid);
341 2242 sgarg
            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 3425 tao
            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 2981 jones
            //System.err.println(response);
352 2242 sgarg
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 2265 sgarg
     * 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 3425 tao
            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 2981 jones
            //System.err.println(response);
392 2265 sgarg
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 1800 tao
     * 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 3212 tao
        	String docid = readIdFromFile(DOCID);
416
            String identifier = docid + ".2";
417 1800 tao
            m.login(anotheruser, anotherpassword);
418 2242 sgarg
            String response = m.update(identifier,
419 1800 tao
                    new StringReader(testdocument), null);
420
            assertTrue(response.indexOf("<success>") == -1);
421 2242 sgarg
422 1800 tao
        } 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 2242 sgarg
435 1800 tao
    /**
436 1795 jones
     * Test the update() function with a known document
437
     */
438
    public void update()
439
    {
440
        try {
441 3212 tao
        	String docid = readIdFromFile(DOCID);
442
            String identifier = docid + ".2";
443 1795 jones
            m.login(username, password);
444 2242 sgarg
            String response = m.update(identifier,
445 1795 jones
                    new StringReader(testdocument), null);
446
            assertTrue(response.indexOf("<success>") != -1);
447
            assertTrue(response.indexOf(identifier) != -1);
448 2981 jones
            //System.err.println(response);
449 1795 jones
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 2242 sgarg
463 1800 tao
    /**
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 2981 jones
            //System.err.println(response);
474 1795 jones
475 1800 tao
        } 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 2242 sgarg
488 1795 jones
    /**
489
     * Test the delete() function with a known document
490
     */
491
    public void delete()
492
    {
493
        try {
494 3212 tao
        	Thread.sleep(10000);
495
        	String docid = readIdFromFile(DOCID);
496
            String identifier = docid + ".2";
497 1795 jones
            m.login(username, password);
498
            String response = m.delete(identifier);
499
            assertTrue(response.indexOf("<success>") != -1);
500 3212 tao
            // delete the docid persistence file.
501
            deleteFile(DOCID);
502
            deleteFile(DATAID);
503 2981 jones
            //System.err.println(response);
504 1795 jones
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 2242 sgarg
518 1800 tao
    /**
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 1826 jones
    public void inaccessibleMetacat()
524 1800 tao
    {
525
        Metacat mWrong = null;
526
        try {
527
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
528
        } catch (MetacatInaccessibleException mie) {
529
            fail("Metacat Inaccessible:\n" + mie.getMessage());
530
        }
531 2242 sgarg
532 1800 tao
        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 1795 jones
541
    /**
542 1826 jones
     * 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 2981 jones
            //System.err.println("SessionId (mtemp): " + oldSessionId);
554 1826 jones
        } 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 1828 jones
            System.err.println("SessionId (m2): " + m2.getSessionId());
571 1826 jones
            m2.setSessionId(oldSessionId);
572 1828 jones
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
573 2242 sgarg
            String response = m2.insert(identifier,
574 1826 jones
                    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 1828 jones
     * Try to perform an action that requires a session to be valid without
590 2242 sgarg
     * having logged in first, but use an invalid session identifier.
591 1829 jones
     * Then insert a document, which should fail.
592 1828 jones
     */
593
    public void reuseInvalidSession()
594
    {
595 1829 jones
        System.err.println("Starting resuseInvalidSession test...");
596 1828 jones
        String oldSessionId = "foobar";
597
        try {
598
            String identifier = generateDocid() + ".1";
599 1829 jones
            Metacat m3 = null;
600 1828 jones
            try {
601 1829 jones
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
602 1828 jones
            } catch (MetacatInaccessibleException mie) {
603
                System.err.println("Metacat is: " + metacatUrl);
604
                fail("Metacat connection failed." + mie.getMessage());
605
            }
606 1829 jones
            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 2242 sgarg
            String response = m3.insert(identifier,
612 1828 jones
                    new StringReader(testdocument), null);
613 1829 jones
            System.err.println("ReuseInvalid Insert response: " + response);
614 1828 jones
            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 2265 sgarg
            if(me.getMessage().
621
               indexOf("Permission denied for user public inser") == -1){
622
                fail("Metacat Error:\n" + me.getMessage());
623
            }
624 1828 jones
        } catch (Exception e) {
625
            fail("General exception:\n" + e.getMessage());
626
        }
627
    }
628 2338 tao
629 2981 jones
   /**
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 2992 berkley
           System.err.println("Last Id: " + lastId);
646 3212 tao
           //get docid from file
647
           String docid = readIdFromFile(DOCID);
648
           assertTrue(lastId.equals(docid + ".1"));
649 2981 jones
       } 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 2338 tao
    * 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 2981 jones
       //System.err.println("Starting getNewestDocRevision test...");
664 2338 tao
       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 3212 tao
           // get docid from file
674
           String docid = readIdFromFile(DOCID);
675
           int revision = m3.getNewestDocRevision(docid);
676 2981 jones
           //System.err.println("Newest revision number is: " + revision);
677 2338 tao
           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 3172 tao
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 3186 tao
	            Thread.sleep(6000);
714
	            String response2 = m.delete(identifier);
715
	            assertTrue(response2.indexOf("<success>") != -1);
716 3172 tao
	            //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 2338 tao
733
    /**
734 1791 jones
     * 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 2988 sgarg
	StringBuffer docid = new StringBuffer(prefix);
742
	docid.append(".");
743
744 1791 jones
        // 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 2988 sgarg
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 3187 tao
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 2988 sgarg
	return docid.toString();
798 1791 jones
    }
799 3212 tao
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 1783 jones
}