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