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