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