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