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 4080 daigle
import edu.ucsb.nceas.metacat.service.PropertyService;
50
import edu.ucsb.nceas.metacat.util.MetaCatUtil;
51
import edu.ucsb.nceas.metacat.util.SystemUtil;
52 2242 sgarg
import edu.ucsb.nceas.utilities.IOUtil;
53 4080 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
54 1783 jones
import junit.framework.Test;
55
import junit.framework.TestCase;
56
import junit.framework.TestSuite;
57 2265 sgarg
import java.io.FileInputStream;
58 1783 jones
59 3172 tao
import org.apache.log4j.Logger;
60
61 1783 jones
/**
62
 * A JUnit test for testing Step class processing
63
 */
64
public class MetacatClientTest extends TestCase
65
{
66 4080 daigle
67 1800 tao
    private String wrongMetacatUrl=
68 4080 daigle
    	"http://somepalce.somewhere.com/some/servlet/metacat";
69
70
    private static String metacatUrl;
71
    private static String username;
72
	private static String password;
73
	private static String anotheruser;
74
	private static String anotherpassword;
75
	static {
76
		try {
77 4126 daigle
		    metacatUrl = PropertyService.getProperty("test.metacat.url");
78
			username = PropertyService.getProperty("test.mcuser");
79
			password = PropertyService.getProperty("test.mcpassword");
80
			anotheruser = PropertyService.getProperty("test.mcanotheruser");
81
			anotherpassword = PropertyService.getProperty("test.mcanotherpassword");
82 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
83
			System.err.println("Could not get property in static block: "
84
					+ pnfe.getMessage());
85
		}
86
	}
87 1783 jones
    private String failpass = "uidfnkj43987yfdn";
88 1791 jones
    private String prefix = "test";
89
    private String newdocid = null;
90 1784 jones
    private String testfile = "test/jones.204.22.xml";
91 2242 sgarg
    private String onlinetestdatafile = "test/onlineDataFile1";
92 1787 tao
    private String queryFile = "test/query.xml";
93 1784 jones
    private String testdocument = "";
94 1783 jones
    private Metacat m;
95 3172 tao
    private String spatialTestFile = "test/spatialEml.xml";
96
    private static final int TIME = 30;
97 3212 tao
    private static final String DOCID = "docid";
98
    private static final String DATAID = "dataid";
99 3172 tao
100 1783 jones
    /**
101
     * Constructor to build the test
102
     *
103
     * @param name the name of the test method
104
     */
105
    public MetacatClientTest(String name)
106
    {
107
        super(name);
108 1791 jones
        newdocid = generateDocid();
109 1783 jones
    }
110
111
    /**
112
     * Establish a testing framework by initializing appropriate objects
113
     */
114
    public void setUp()
115
    {
116
        try {
117 1784 jones
            FileReader fr = new FileReader(testfile);
118 1788 jones
            testdocument = IOUtil.getAsString(fr, true);
119 1784 jones
        } catch (IOException ioe) {
120
            fail("Can't read test data to run the test: " + testfile);
121
        }
122
123
        try {
124 1828 jones
            System.err.println("Test Metacat: " + metacatUrl);
125 1783 jones
            m = MetacatFactory.createMetacatConnection(metacatUrl);
126
        } catch (MetacatInaccessibleException mie) {
127 1822 jones
            System.err.println("Metacat is: " + metacatUrl);
128 1783 jones
            fail("Metacat connection failed." + mie.getMessage());
129
        }
130
    }
131 2242 sgarg
132 1783 jones
    /**
133
     * Release any objects after tests are complete
134
     */
135
    public void tearDown()
136
    {
137
    }
138 2242 sgarg
139 1783 jones
    /**
140
     * Create a suite of tests to be run together
141
     */
142
    public static Test suite()
143
    {
144 2242 sgarg
      TestSuite suite = new TestSuite();
145 2265 sgarg
      suite.addTest(new MetacatClientTest("initialize"));
146 2987 sgarg
      suite.addTest(new MetacatClientTest("invalidLogin"));
147
      suite.addTest(new MetacatClientTest("logoutAndInvalidInsert"));
148 2265 sgarg
      suite.addTest(new MetacatClientTest("login"));
149
      suite.addTest(new MetacatClientTest("insert"));
150 2987 sgarg
      suite.addTest(new MetacatClientTest("getNewestDocRevision"));
151 2981 jones
      suite.addTest(new MetacatClientTest("getLastDocid"));
152 2987 sgarg
      suite.addTest(new MetacatClientTest("upload"));
153
      suite.addTest(new MetacatClientTest("upload_stream"));
154
      suite.addTest(new MetacatClientTest("invalidRead"));
155
      suite.addTest(new MetacatClientTest("read"));
156
      suite.addTest(new MetacatClientTest("query"));
157 3465 tao
      suite.addTest(new MetacatClientTest("queryWithQformat"));
158 2987 sgarg
      suite.addTest(new MetacatClientTest("invalidUpdate"));
159
      suite.addTest(new MetacatClientTest("update"));
160
      suite.addTest(new MetacatClientTest("invalidDelete"));
161
      suite.addTest(new MetacatClientTest("delete"));
162
      suite.addTest(new MetacatClientTest("inaccessibleMetacat"));
163
      suite.addTest(new MetacatClientTest("reuseSession"));
164
      suite.addTest(new MetacatClientTest("reuseInvalidSession"));
165 3172 tao
      //suite.addTest(new MetacatClientTest("insertSpatialDocs"));
166 2265 sgarg
      return suite;
167
  }
168 2242 sgarg
169 1783 jones
    /**
170
     * Run an initial test that always passes to check that the test
171
     * harness is working.
172
     */
173
    public void initialize()
174
    {
175
        assertTrue(1 == 1);
176
    }
177 2242 sgarg
178 1783 jones
    /**
179
     * Test the login() function with valid credentials
180
     */
181
    public void login()
182
    {
183
        // Try a valid login
184
        try {
185 1822 jones
            String response = m.login(username, password);
186 2981 jones
            //System.err.println("Login response: " + response);
187 1822 jones
            assertTrue(response != null);
188
            assertTrue(response.indexOf("<login>") != -1);
189
            String sessionId = m.getSessionId();
190 2981 jones
            //System.err.println("Session ID: " + m.getSessionId());
191 1825 jones
            assertTrue(sessionId != null);
192
            assertTrue(response.indexOf(m.getSessionId()) != -1);
193 1783 jones
        } catch (MetacatAuthException mae) {
194
            fail("Authorization failed:\n" + mae.getMessage());
195
        } catch (MetacatInaccessibleException mie) {
196
            fail("Metacat Inaccessible:\n" + mie.getMessage());
197
        }
198
    }
199
200
    /**
201
     * Test the login() function with INVALID credentials
202
     */
203
    public void invalidLogin()
204
    {
205
        // Try an invalid login
206
        try {
207
            m.login(username, failpass);
208
            fail("Authorization should have failed.");
209
        } catch (MetacatAuthException mae) {
210
            assertTrue(1 == 1);
211
        } catch (MetacatInaccessibleException mie) {
212
            fail("Metacat Inaccessible:\n" + mie.getMessage());
213
        }
214
    }
215 2242 sgarg
216 1800 tao
    /**
217
     * Test the logout() function. When logout, user will be public, it couldn't
218
     * insert a document.
219
     */
220
    public void logoutAndInvalidInsert()
221
    {
222
       try {
223
            String identifier = newdocid + ".1";
224
            m.login(username, password);
225
            m.logout();
226 2242 sgarg
            String response = m.insert(identifier,
227 1800 tao
                    new StringReader(testdocument), null);
228 2981 jones
            //System.err.println("Response in logout: "+response);
229 1800 tao
            assertTrue(response.indexOf("<success>") == -1);
230
        } catch (MetacatAuthException mae) {
231
            fail("Authorization failed:\n" + mae.getMessage());
232
        } catch (MetacatInaccessibleException mie) {
233
            fail("Metacat Inaccessible:\n" + mie.getMessage());
234
        } catch (InsufficientKarmaException ike) {
235
            fail("Insufficient karma:\n" + ike.getMessage());
236
        } catch (MetacatException me) {
237 2265 sgarg
            if(me.getMessage().
238
              indexOf("Permission denied for user public inser") == -1){
239
               fail("Metacat Error:\n" + me.getMessage());
240
           }
241 1800 tao
        } catch (Exception e) {
242
            fail("General exception:\n" + e.getMessage());
243
        }
244
    }
245 1784 jones
246
    /**
247
     * Test the read() function with a known document
248
     */
249
    public void read()
250
    {
251
        try {
252
            m.login(username, password);
253 3212 tao
            String docid = readIdFromFile(DOCID);
254
            Reader r = m.read(docid+".1");
255 1788 jones
            String doc = IOUtil.getAsString(r, true);
256 1800 tao
            doc = doc +"\n";
257 2981 jones
            //System.err.println(doc);
258 1784 jones
            assertTrue(doc.equals(testdocument));
259
        } catch (MetacatAuthException mae) {
260
            fail("Authorization failed:\n" + mae.getMessage());
261
        } catch (MetacatInaccessibleException mie) {
262
            fail("Metacat Inaccessible:\n" + mie.getMessage());
263
        } catch (Exception e) {
264
            fail("General exception:\n" + e.getMessage());
265
        }
266
    }
267 2242 sgarg
268 1787 tao
    /**
269 1800 tao
     * A user try to read a document which it doesn't have read permission
270
     */
271
    public void invalidRead()
272
    {
273
        try {
274
            m.login(anotheruser, anotherpassword);
275 3212 tao
            String docid = readIdFromFile(DOCID);
276
            Reader r = m.read(docid+".1");
277 1800 tao
            String doc = IOUtil.getAsString(r, true);
278
            assertTrue(doc.indexOf("<error>") != -1);
279 2981 jones
            //System.err.println(doc);
280 1800 tao
        } catch (MetacatAuthException mae) {
281
            fail("Authorization failed:\n" + mae.getMessage());
282
        } catch (MetacatInaccessibleException mie) {
283
            fail("Metacat Inaccessible:\n" + mie.getMessage());
284
        } catch (InsufficientKarmaException ike) {
285
            assertTrue(1 == 1);
286
        } catch (MetacatException e) {
287
            fail("Metacat exception:\n" + e.getMessage());
288 3172 tao
        } catch (IOException ioe) {
289
            fail("IO exception:\n" + ioe.getMessage());
290
        } catch (DocumentNotFoundException ne) {
291
            fail("DocumentNotFound exception:\n" + ne.getMessage());
292
293 3212 tao
        } catch(Exception e) {
294
            fail("Exception:\n" + e.getMessage());
295 1800 tao
        }
296
    }
297 2242 sgarg
298 1800 tao
    /**
299 1787 tao
     * Test the query() function with a known document
300
     */
301
    public void query()
302
    {
303
        try {
304 1828 jones
            m.login(username,password);
305 1787 tao
            FileReader fr = new FileReader(queryFile);
306
            Reader r = m.query(fr);
307 2981 jones
            //System.err.println("Starting query...");
308 1788 jones
            String result = IOUtil.getAsString(r, true);
309 3465 tao
            System.err.println("Query result:\n" + result);
310 3212 tao
            String docid = readIdFromFile(DOCID);
311
            assertTrue(result.indexOf(docid+".1")!=-1);
312 3465 tao
            assertTrue(result.indexOf("<?xml")!=-1);
313 1828 jones
        } catch (MetacatAuthException mae) {
314
            fail("Authorization failed:\n" + mae.getMessage());
315 1787 tao
        } catch (MetacatInaccessibleException mie) {
316
            fail("Metacat Inaccessible:\n" + mie.getMessage());
317
        } catch (Exception e) {
318
            fail("General exception:\n" + e.getMessage());
319
        }
320
    }
321 3465 tao
    /**
322
     * Test the query() function with a known document
323
     */
324
    public void queryWithQformat()
325
    {
326
        try {
327
            m.login(username,password);
328
            FileReader fr = new FileReader(queryFile);
329
            String qformat = "knb";
330
            Reader r = m.query(fr, qformat);
331
            //System.err.println("Starting query...");
332
            String result = IOUtil.getAsString(r, true);
333
            System.err.println("Query result:\n" + result);
334
            String docid = readIdFromFile(DOCID);
335
            assertTrue(result.indexOf(docid+".1")!=-1);
336
            assertTrue(result.indexOf("<html>")!=-1);
337
        } catch (MetacatAuthException mae) {
338
            fail("Authorization failed:\n" + mae.getMessage());
339
        } catch (MetacatInaccessibleException mie) {
340
            fail("Metacat Inaccessible:\n" + mie.getMessage());
341
        } catch (Exception e) {
342
            fail("General exception:\n" + e.getMessage());
343
        }
344
    }
345 1789 jones
346
    /**
347
     * Test the insert() function with a known document
348
     */
349
    public void insert()
350
    {
351
        try {
352 1791 jones
            String identifier = newdocid + ".1";
353 3212 tao
            //write newdocid into file for persistance
354
            writeIdToFile(DOCID, newdocid);
355 1789 jones
            m.login(username, password);
356 2242 sgarg
            String response = m.insert(identifier,
357 1789 jones
                    new StringReader(testdocument), null);
358
            assertTrue(response.indexOf("<success>") != -1);
359 1791 jones
            assertTrue(response.indexOf(identifier) != -1);
360 2981 jones
            //System.err.println(response);
361 1789 jones
362
        } catch (MetacatAuthException mae) {
363
            fail("Authorization failed:\n" + mae.getMessage());
364
        } catch (MetacatInaccessibleException mie) {
365
            fail("Metacat Inaccessible:\n" + mie.getMessage());
366
        } catch (InsufficientKarmaException ike) {
367 1800 tao
            assertTrue(1 == 1);
368 1789 jones
            fail("Insufficient karma:\n" + ike.getMessage());
369
        } catch (MetacatException me) {
370
            fail("Metacat Error:\n" + me.getMessage());
371
        } catch (Exception e) {
372
            fail("General exception:\n" + e.getMessage());
373
        }
374
    }
375 1791 jones
376
    /**
377 3779 tao
     * Test the upload() function with a data file.
378
     * 1. Insert version 1 successfully.
379
     * 2. Update version 2 successfully
380
     * 3. Update version 2 again and should be failed.
381 2242 sgarg
     */
382
    public void upload()
383
    {
384
        try {
385
            newdocid = generateDocid();
386
            String identifier = newdocid + ".1";
387 3212 tao
            writeIdToFile(DATAID, newdocid);
388 2242 sgarg
            m.login(username, password);
389
            String response = m.upload(identifier,
390
                                     new File(onlinetestdatafile));
391
            assertTrue(response.indexOf("<success>") != -1);
392
            assertTrue(response.indexOf(identifier) != -1);
393 3425 tao
            identifier = newdocid +".2";
394
            response = m.upload(identifier,
395
                    new File(onlinetestdatafile));
396
            assertTrue(response.indexOf("<success>") != -1);
397
            assertTrue(response.indexOf(identifier) != -1);
398 2981 jones
            //System.err.println(response);
399 3779 tao
            //upload the same identifier again. it should return an error
400
            try
401
            {
402
                response = m.upload(identifier,
403
                      new File(onlinetestdatafile));
404
                fail("Metacat shouldn't successfully upload the same identifier twice "+response);
405
            }
406
            catch(Exception ee)
407
            {
408
                assertTrue(ee.getMessage().indexOf("<error>") != -1);
409
            }
410 2242 sgarg
411
        } catch (MetacatAuthException mae) {
412
            fail("Authorization failed:\n" + mae.getMessage());
413
        } catch (MetacatInaccessibleException mie) {
414
          mie.printStackTrace();
415
            fail("Metacat Inaccessible:\n" + mie.getMessage());
416
        } catch (InsufficientKarmaException ike) {
417
            assertTrue(1 == 1);
418
            fail("Insufficient karma:\n" + ike.getMessage());
419
        } catch (MetacatException me) {
420
            fail("Metacat Error:\n" + me.getMessage());
421
        } catch (Exception e) {
422
            fail("General exception:\n" + e.getMessage());
423
        }
424
    }
425 3779 tao
426 2242 sgarg
427 3779 tao
428 2242 sgarg
    /**
429 2265 sgarg
     * Test the upload() function by passing an InputStream
430
     */
431
    public void upload_stream()
432
    {
433
        try {
434
            newdocid = generateDocid();
435
            String identifier = newdocid + ".1";
436
            m.login(username, password);
437
            File testFile = new File(onlinetestdatafile);
438
            String response = m.upload(identifier, "onlineDataFile1",
439
                                       new FileInputStream(testFile),
440
                                       (int) testFile.length());
441
442
            assertTrue(response.indexOf("<success>") != -1);
443
            assertTrue(response.indexOf(identifier) != -1);
444 3425 tao
            identifier = newdocid + ".2";
445
            response = m.upload(identifier, "onlineDataFile1",
446
                    new FileInputStream(testFile),
447
                    (int) testFile.length());
448
449
           assertTrue(response.indexOf("<success>") != -1);
450
           assertTrue(response.indexOf(identifier) != -1);
451 2981 jones
            //System.err.println(response);
452 2265 sgarg
453
        } catch (MetacatAuthException mae) {
454
            fail("Authorization failed:\n" + mae.getMessage());
455
        } catch (MetacatInaccessibleException mie) {
456
          mie.printStackTrace();
457
            fail("Metacat Inaccessible:\n" + mie.getMessage());
458
        } catch (InsufficientKarmaException ike) {
459
            assertTrue(1 == 1);
460
            fail("Insufficient karma:\n" + ike.getMessage());
461
        } catch (MetacatException me) {
462
            fail("Metacat Error:\n" + me.getMessage());
463
        } catch (Exception e) {
464
            fail("General exception:\n" + e.getMessage());
465
        }
466
    }
467
468
    /**
469 1800 tao
     * Test the invalidUpdate() function. A user try to update a document
470
     * which it doesn't have permission
471
     */
472
    public void invalidUpdate()
473
    {
474
        try {
475 3212 tao
        	String docid = readIdFromFile(DOCID);
476
            String identifier = docid + ".2";
477 1800 tao
            m.login(anotheruser, anotherpassword);
478 2242 sgarg
            String response = m.update(identifier,
479 1800 tao
                    new StringReader(testdocument), null);
480
            assertTrue(response.indexOf("<success>") == -1);
481 2242 sgarg
482 1800 tao
        } catch (MetacatAuthException mae) {
483
            fail("Authorization failed:\n" + mae.getMessage());
484
        } catch (MetacatInaccessibleException mie) {
485
            fail("Metacat Inaccessible:\n" + mie.getMessage());
486
        } catch (InsufficientKarmaException ike) {
487
            assertTrue(1 == 1);
488
        } catch (MetacatException me) {
489
            fail("Metacat Error:\n" + me.getMessage());
490
        } catch (Exception e) {
491
            fail("General exception:\n" + e.getMessage());
492
        }
493
    }
494 2242 sgarg
495 1800 tao
    /**
496 1795 jones
     * Test the update() function with a known document
497
     */
498
    public void update()
499
    {
500
        try {
501 3212 tao
        	String docid = readIdFromFile(DOCID);
502
            String identifier = docid + ".2";
503 1795 jones
            m.login(username, password);
504 2242 sgarg
            String response = m.update(identifier,
505 1795 jones
                    new StringReader(testdocument), null);
506
            assertTrue(response.indexOf("<success>") != -1);
507
            assertTrue(response.indexOf(identifier) != -1);
508 2981 jones
            //System.err.println(response);
509 1795 jones
510
        } catch (MetacatAuthException mae) {
511
            fail("Authorization failed:\n" + mae.getMessage());
512
        } catch (MetacatInaccessibleException mie) {
513
            fail("Metacat Inaccessible:\n" + mie.getMessage());
514
        } catch (InsufficientKarmaException ike) {
515
            fail("Insufficient karma:\n" + ike.getMessage());
516
        } catch (MetacatException me) {
517
            fail("Metacat Error:\n" + me.getMessage());
518
        } catch (Exception e) {
519
            fail("General exception:\n" + e.getMessage());
520
        }
521
    }
522 2242 sgarg
523 1800 tao
    /**
524
     * A user try delete a document which it doesn't have permission
525
     */
526
    public void invalidDelete()
527
    {
528
        try {
529
            String identifier = newdocid + ".2";
530
            m.login(anotheruser, anotherpassword);
531
            String response = m.delete(identifier);
532
            assertTrue(response.indexOf("<success>") == -1);
533 2981 jones
            //System.err.println(response);
534 1795 jones
535 1800 tao
        } catch (MetacatAuthException mae) {
536
            fail("Authorization failed:\n" + mae.getMessage());
537
        } catch (MetacatInaccessibleException mie) {
538
            fail("Metacat Inaccessible:\n" + mie.getMessage());
539
        } catch (InsufficientKarmaException ike) {
540
            assertTrue(1 == 1);
541
        } catch (MetacatException me) {
542
            assertTrue(1 == 1);
543
        } catch (Exception e) {
544
            fail("General exception:\n" + e.getMessage());
545
        }
546
    }
547 2242 sgarg
548 1795 jones
    /**
549
     * Test the delete() function with a known document
550
     */
551
    public void delete()
552
    {
553
        try {
554 3212 tao
        	Thread.sleep(10000);
555
        	String docid = readIdFromFile(DOCID);
556
            String identifier = docid + ".2";
557 1795 jones
            m.login(username, password);
558
            String response = m.delete(identifier);
559
            assertTrue(response.indexOf("<success>") != -1);
560 3212 tao
            // delete the docid persistence file.
561
            deleteFile(DOCID);
562
            deleteFile(DATAID);
563 2981 jones
            //System.err.println(response);
564 1795 jones
565
        } catch (MetacatAuthException mae) {
566
            fail("Authorization failed:\n" + mae.getMessage());
567
        } catch (MetacatInaccessibleException mie) {
568
            fail("Metacat Inaccessible:\n" + mie.getMessage());
569
        } catch (InsufficientKarmaException ike) {
570
            fail("Insufficient karma:\n" + ike.getMessage());
571
        } catch (MetacatException me) {
572
            fail("Metacat Error:\n" + me.getMessage());
573
        } catch (Exception e) {
574
            fail("General exception:\n" + e.getMessage());
575
        }
576
    }
577 2242 sgarg
578 1800 tao
    /**
579
     * Test the to connect a wrong metacat url. Create a new metacat with a
580
     * inaccessible url. Then try to login it. If get a MetacatInaccessible
581
     * exception, this is right.
582
     */
583 1826 jones
    public void inaccessibleMetacat()
584 1800 tao
    {
585
        Metacat mWrong = null;
586
        try {
587
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
588
        } catch (MetacatInaccessibleException mie) {
589
            fail("Metacat Inaccessible:\n" + mie.getMessage());
590
        }
591 2242 sgarg
592 1800 tao
        try {
593
            mWrong.login(username, password);
594
        } catch (MetacatInaccessibleException mie) {
595
            assertTrue(1 == 1);
596
        } catch (MetacatAuthException mae) {
597
            fail("Authorization failed:\n" + mae.getMessage());
598
        }
599
    }
600 1795 jones
601
    /**
602 1826 jones
     * Try to perform an action that requires a session to be valid without
603
     * having logged in first by setting the sessionId from a previous
604
     * session.  Then insert a document.
605
     */
606
    public void reuseSession()
607
    {
608
        String oldSessionId = "";
609
        try {
610
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
611
            String response = mtemp.login(username, password);
612
            oldSessionId = mtemp.getSessionId();
613 2981 jones
            //System.err.println("SessionId (mtemp): " + oldSessionId);
614 1826 jones
        } catch (MetacatAuthException mae) {
615
            fail("Authorization failed:\n" + mae.getMessage());
616
        } catch (MetacatInaccessibleException mie) {
617
            System.err.println("Metacat is: " + metacatUrl);
618
            fail("Metacat connection failed." + mie.getMessage());
619
        }
620
621
        try {
622
            String identifier = generateDocid() + ".1";
623
            Metacat m2 = null;
624
            try {
625
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
626 3588 tao
                m2.logout();
627 1826 jones
            } catch (MetacatInaccessibleException mie) {
628
                System.err.println("Metacat is: " + metacatUrl);
629
                fail("Metacat connection failed." + mie.getMessage());
630
            }
631 1828 jones
            System.err.println("SessionId (m2): " + m2.getSessionId());
632 1826 jones
            m2.setSessionId(oldSessionId);
633 1828 jones
            System.err.println("SessionId (m2 after set): " + m2.getSessionId());
634 2242 sgarg
            String response = m2.insert(identifier,
635 1826 jones
                    new StringReader(testdocument), null);
636
            System.err.println("Reuse Insert response: " + response);
637
            assertTrue(response.indexOf("<success>") != -1);
638
        } catch (MetacatInaccessibleException mie) {
639
            fail("Metacat Inaccessible:\n" + mie.getMessage());
640
        } catch (InsufficientKarmaException ike) {
641
            fail("Insufficient karma:\n" + ike.getMessage());
642
        } catch (MetacatException me) {
643
            fail("Metacat Error:\n" + me.getMessage());
644
        } catch (Exception e) {
645
            fail("General exception:\n" + e.getMessage());
646
        }
647
    }
648
649
    /**
650 1828 jones
     * Try to perform an action that requires a session to be valid without
651 2242 sgarg
     * having logged in first, but use an invalid session identifier.
652 1829 jones
     * Then insert a document, which should fail.
653 1828 jones
     */
654
    public void reuseInvalidSession()
655
    {
656 1829 jones
        System.err.println("Starting resuseInvalidSession test...");
657 1828 jones
        String oldSessionId = "foobar";
658
        try {
659
            String identifier = generateDocid() + ".1";
660 1829 jones
            Metacat m3 = null;
661 1828 jones
            try {
662 1829 jones
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
663 3588 tao
                m3.logout();
664 1828 jones
            } catch (MetacatInaccessibleException mie) {
665
                System.err.println("Metacat is: " + metacatUrl);
666
                fail("Metacat connection failed." + mie.getMessage());
667
            }
668 1829 jones
            System.err.println("SessionId (m3): " + m3.getSessionId());
669
            m3.setSessionId(oldSessionId);
670
            System.err.println("SessionId (m3 after set): " + m3.getSessionId());
671
            System.err.println("Performing resuseInvalidSession insert: " +
672
                    identifier);
673 2242 sgarg
            String response = m3.insert(identifier,
674 1828 jones
                    new StringReader(testdocument), null);
675 1829 jones
            System.err.println("ReuseInvalid Insert response: " + response);
676 1828 jones
            assertTrue(response.indexOf("<success>") == -1);
677
        } catch (MetacatInaccessibleException mie) {
678
            fail("Metacat Inaccessible:\n" + mie.getMessage());
679
        } catch (InsufficientKarmaException ike) {
680
            fail("Insufficient karma:\n" + ike.getMessage());
681
        } catch (MetacatException me) {
682 2265 sgarg
            if(me.getMessage().
683
               indexOf("Permission denied for user public inser") == -1){
684
                fail("Metacat Error:\n" + me.getMessage());
685
            }
686 1828 jones
        } catch (Exception e) {
687
            fail("General exception:\n" + e.getMessage());
688
        }
689
    }
690 2338 tao
691 2981 jones
   /**
692
    * Get the most recent document id for a given scope and be sure
693
    * that it matches the one we last inserted. Assumes this test is run
694
    * immediately following a successful insert() test.
695
    */
696
   public void getLastDocid()
697
   {
698
       try {
699
           Metacat m3 = null;
700
           try {
701
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
702
           } catch (MetacatInaccessibleException mie) {
703
               System.err.println("Metacat is: " + metacatUrl);
704
               fail("Metacat connection failed." + mie.getMessage());
705
           }
706
           String lastId = m3.getLastDocid(prefix);
707 2992 berkley
           System.err.println("Last Id: " + lastId);
708 3212 tao
           //get docid from file
709
           String docid = readIdFromFile(DOCID);
710
           assertTrue(lastId.equals(docid + ".1"));
711 2981 jones
       } catch (MetacatException me) {
712
           fail("Metacat Error:\n" + me.getMessage());
713
       } catch (Exception e) {
714
           fail("General exception:\n" + e.getMessage());
715
       }
716
   }
717
718
   /**
719 2338 tao
    * Try to perform an action that requires a session to be valid without
720
    * having logged in first, but use an invalid session identifier.
721
    * Then insert a document, which should fail.
722
    */
723
   public void getNewestDocRevision()
724
   {
725 2981 jones
       //System.err.println("Starting getNewestDocRevision test...");
726 2338 tao
       try {
727
728
           Metacat m3 = null;
729
           try {
730
               m3 = MetacatFactory.createMetacatConnection(metacatUrl);
731
           } catch (MetacatInaccessibleException mie) {
732
               System.err.println("Metacat is: " + metacatUrl);
733
               fail("Metacat connection failed." + mie.getMessage());
734
           }
735 3212 tao
           // get docid from file
736
           String docid = readIdFromFile(DOCID);
737
           int revision = m3.getNewestDocRevision(docid);
738 2981 jones
           //System.err.println("Newest revision number is: " + revision);
739 2338 tao
           assertTrue(revision == 1);
740
       } catch (MetacatException me) {
741
           if(me.getMessage().
742
              indexOf("Permission denied for user public inser") == -1){
743
               fail("Metacat Error:\n" + me.getMessage());
744
           }
745
       } catch (Exception e) {
746
           fail("General exception:\n" + e.getMessage());
747
       }
748
   }
749 3172 tao
750
   /**
751
    * Try to insert a bunch of eml documents which contain spatial information
752
    * This test is used to try to find a bug in spatial part of metacat
753
    */
754
    public void insertSpatialDocs() throws IOException
755
    {
756
    	FileReader fr = new FileReader(spatialTestFile);
757
        String spatialtestdocument = IOUtil.getAsString(fr, true);
758
        System.out.println("the eml is "+spatialtestdocument);
759
    	for (int i=0; i<TIME; i++)
760
    	{
761
	    	try {
762
	    		newdocid = generateDocid();
763
	            String identifier = newdocid + ".1";
764
	            System.out.println("the docid is "+identifier);
765
	            m.login(username, password);
766
	            String response = m.insert(identifier,
767
	                    new StringReader(spatialtestdocument), null);
768
	            assertTrue(response.indexOf("<success>") != -1);
769
	            assertTrue(response.indexOf(identifier) != -1);
770
	            Thread.sleep(8000);
771
	            identifier = newdocid +".2";
772
	            response = m.update(identifier,
773
	                    new StringReader(spatialtestdocument), null);
774
	            assertTrue(response.indexOf("<success>") != -1);
775 3186 tao
	            Thread.sleep(6000);
776
	            String response2 = m.delete(identifier);
777
	            assertTrue(response2.indexOf("<success>") != -1);
778 3172 tao
	            //System.err.println(response);
779
780
	        } catch (MetacatAuthException mae) {
781
	            fail("Authorization failed:\n" + mae.getMessage());
782
	        } catch (MetacatInaccessibleException mie) {
783
	            fail("Metacat Inaccessible:\n" + mie.getMessage());
784
	        } catch (InsufficientKarmaException ike) {
785
	            assertTrue(1 == 1);
786
	            fail("Insufficient karma:\n" + ike.getMessage());
787
	        } catch (MetacatException me) {
788
	            fail("Metacat Error:\n" + me.getMessage());
789
	        } catch (Exception e) {
790
	            fail("General exception:\n" + e.getMessage());
791
	        }
792
    	}
793
    }
794 2338 tao
795
    /**
796 1791 jones
     * Create a hopefully unique docid for testing insert and update. Does
797
     * not include the 'revision' part of the id.
798
     *
799
     * @return a String docid based on the current date and time
800
     */
801
    private String generateDocid()
802
    {
803 2988 sgarg
	StringBuffer docid = new StringBuffer(prefix);
804
	docid.append(".");
805
806 1791 jones
        // Create a calendar to get the date formatted properly
807
        String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
808
        SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
809
        pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);
810
        pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
811
        Calendar calendar = new GregorianCalendar(pdt);
812
        Date trialTime = new Date();
813
        calendar.setTime(trialTime);
814 2988 sgarg
815
	int time = 0;
816
817
	docid.append(calendar.get(Calendar.YEAR));
818
819
	time = calendar.get(Calendar.DAY_OF_YEAR);
820
	if(time < 10){
821
		docid.append("0");
822
		docid.append("0");
823
		docid.append(time);
824
	} else if(time < 100) {
825
		docid.append("0");
826
		docid.append(time);
827
	} else {
828
		docid.append(time);
829
	}
830
831
	time = calendar.get(Calendar.HOUR_OF_DAY);
832
	if(time < 10){
833
		docid.append("0");
834
		docid.append(time);
835
	} else {
836
		docid.append(time);
837
	}
838
839
	time = calendar.get(Calendar.MINUTE);
840
	if(time < 10){
841
		docid.append("0");
842
		docid.append(time);
843
	} else {
844
		docid.append(time);
845
	}
846
847
	time = calendar.get(Calendar.SECOND);
848
	if(time < 10){
849
		docid.append("0");
850
		docid.append(time);
851
	} else {
852
		docid.append(time);
853
	}
854 3187 tao
855
	 //sometimes this number is not unique, so we append a random number
856
	int random = (new Double(Math.random()*100)).intValue();
857
	docid.append(random);
858
859 2988 sgarg
	return docid.toString();
860 1791 jones
    }
861 3212 tao
862
    /*
863
     * Write id to a file for persistance
864
     */
865
    private void writeIdToFile(String fileName, String id) throws Exception
866
    {
867
    	File file = new File(fileName);
868
    	StringReader reader = new StringReader(id);
869
    	FileWriter writer = new FileWriter(file);
870
    	char [] buffer = new char[1024];
871
    	int c = reader.read(buffer);
872
    	while (c != -1)
873
    	{
874
    		writer.write(buffer, 0, c);
875
    		c = reader.read(buffer);
876
    	}
877
    	writer.close();
878
    	reader.close();
879
    }
880
881
    /*
882
     * Read id from a given file
883
     */
884
    private String readIdFromFile(String fileName) throws Exception
885
    {
886
    	File file = new File(fileName);
887
    	FileReader reader = new FileReader(file);
888
    	StringWriter writer = new StringWriter();
889
    	char [] buffer = new char[1024];
890
    	int c = reader.read(buffer);
891
    	while (c != -1)
892
    	{
893
    		writer.write(buffer, 0, c);
894
    		c = reader.read(buffer);
895
    	}
896
    	reader.close();
897
    	return writer.toString();
898
    }
899
900
    /*
901
     * Delete the given file
902
     */
903
    private void deleteFile(String fileName) throws Exception
904
    {
905
    	File file = new File(fileName);
906
    	file.delete();
907
    }
908 1783 jones
}