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