Project

General

Profile

1
/**
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: leinfelder $'
8
 *     '$Date: 2014-04-24 13:28:01 -0700 (Thu, 24 Apr 2014) $'
9
 * '$Revision: 8748 $'
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
import java.io.File;
29
import java.io.FileReader;
30
import java.io.FileWriter;
31
import java.io.InputStream;
32
import java.io.InputStreamReader;
33
import java.io.IOException;
34
import java.io.Reader;
35
import java.io.StringReader;
36
import java.io.StringWriter;
37

    
38
import edu.ucsb.nceas.MCTestCase;
39
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
40
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
import edu.ucsb.nceas.metacat.properties.PropertyService;
47
import edu.ucsb.nceas.utilities.IOUtil;
48
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
49
import junit.framework.Test;
50
import junit.framework.TestSuite;
51
import java.io.FileInputStream;
52

    
53
import org.apache.commons.io.IOUtils;
54

    
55

    
56
/**
57
 * A JUnit test for testing Step class processing
58
 */
59
public class MetacatClientTest extends MCTestCase
60
{
61

    
62
    private String wrongMetacatUrl=
63
    	"http://localhostBAD/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
		    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
		} catch (PropertyNotFoundException pnfe) {
78
			System.err.println("Could not get property in static block: " 
79
					+ pnfe.getMessage());
80
		}
81
	}
82
    private String failpass = "uidfnkj43987yfdn";
83
    private String newdocid = null;
84
    private String testfile = "test/jones.204.22.xml";
85
    private String testEMLWithAccess = "test/tao.14563.1.xml";
86
    private String onlinetestdatafile = "test/onlineDataFile1";
87
    private String queryFile = "test/query.xml";
88
    private String testdocument = "";
89
    private Metacat m;
90
    private String spatialTestFile = "test/spatialEml.xml";
91
    private static final int TIME = 5;
92
    private static final String DOCID = "docid";
93
    private static final String DATAID = "dataid";
94
    
95
    /**
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
        // 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
        prefix = "metacatClientTest";
108
        newdocid = generateDocumentId();
109
    }
110

    
111
    /**
112
     * Establish a testing framework by initializing appropriate objects
113
     */
114
    public void setUp()
115
    {
116
        FileInputStream fis = null;
117
        try {
118
        	fis = new FileInputStream(testfile);
119
            testdocument = IOUtils.toString(fis);
120
            fis.close();
121
        } catch (IOException ioe) {
122
            fail("Can't read test data to run the test: " + testfile);
123
        } finally {
124
            IOUtils.closeQuietly(fis);
125
        }
126

    
127
        try {
128
            debug("Test Metacat: " + metacatUrl);
129
            m = MetacatFactory.createMetacatConnection(metacatUrl);
130
        } catch (MetacatInaccessibleException mie) {
131
            System.err.println("Metacat is: " + metacatUrl);
132
            fail("Metacat connection failed." + mie.getMessage());
133
        }
134
    }
135

    
136
    /**
137
     * Release any objects after tests are complete
138
     */
139
    public void tearDown()
140
    {
141
    }
142

    
143
    /**
144
     * Create a suite of tests to be run together
145
     */
146
    public static Test suite()
147
    {
148
      TestSuite suite = new TestSuite();     
149
      suite.addTest(new MetacatClientTest("initialize"));
150
      suite.addTest(new MetacatClientTest("invalidLogin"));
151
      suite.addTest(new MetacatClientTest("logoutAndInvalidInsert"));
152
      suite.addTest(new MetacatClientTest("login"));
153
      suite.addTest(new MetacatClientTest("insert"));
154
      suite.addTest(new MetacatClientTest("getLastDocid"));  // needs to directly follow insert test!!
155
      suite.addTest(new MetacatClientTest("getNewestDocRevision"));  // (also tries to insert)
156
      suite.addTest(new MetacatClientTest("upload"));
157
      suite.addTest(new MetacatClientTest("upload_stream"));
158
      suite.addTest(new MetacatClientTest("upload_stream_chunked"));
159
      suite.addTest(new MetacatClientTest("invalidRead"));
160
      suite.addTest(new MetacatClientTest("read"));
161
      suite.addTest(new MetacatClientTest("query"));
162
      suite.addTest(new MetacatClientTest("queryWithQformat"));
163
      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
      suite.addTest(new MetacatClientTest("insertSpatialDocs"));
171
      suite.addTest(new MetacatClientTest("getAccessControl"));
172
      suite.addTest(new MetacatClientTest("getAccessControlFromDocWithoutAccess"));
173
      return suite;
174
  }
175

    
176
    /**
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

    
185
    /**
186
     * Test the login() function with valid credentials
187
     */
188
    public void login()
189
    {
190
        debug("\nStarting login test...");
191
        // Try a valid login
192
        try {
193
            String response = m.login(username, password);
194
            debug("login(): response=" + response);
195
            assertTrue(response != null);
196
            assertTrue(response.indexOf("<login>") != -1);
197
            String sessionId = m.getSessionId();
198
            debug("login(): Session ID=" + m.getSessionId());
199
            assertTrue(sessionId != null);
200
            assertTrue(response.indexOf(m.getSessionId()) != -1);
201
        } 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
        debug("\nStarting invalidLogin test...");
214
        // 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

    
225
    /**
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
       debug("\nStarting logoutAndInvalidInsert test...");
232
       try {
233
            String identifier = newdocid + ".1";
234
            m.login(username, password);
235
            m.logout();
236
            String response = m.insert(identifier,
237
                    new StringReader(testdocument), null);
238
            debug("logoutAndInvalidInsert(): Response in logout="+response);
239
            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
            if(me.getMessage().
248
              indexOf("Permission denied for user public inser") == -1){
249
               fail("Metacat Error:\n" + me.getMessage());
250
           }
251
        } catch (Exception e) {
252
            fail("General exception:\n" + e.getMessage());
253
        }
254
    }
255

    
256
    /**
257
     * Test the read() function with a known document
258
     */
259
    public void read()
260
    {
261
        debug("\nStarting read test...");
262
        try {
263
            m.login(username, password);
264
            String docid = readIdFromFile(DOCID);
265
            debug("docid=" + docid);
266
            InputStream is = m.read(docid+".1");
267
            String doc = IOUtils.toString(is);
268
            // why oh why were we adding a newline??
269
            //doc = doc +"\n";
270
            if (!doc.equals(testdocument)) {
271
                debug("doc         :" + doc + "EOF");
272
                debug("testdocument:" + testdocument + "EOF");
273
            }
274
            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

    
284
    /**
285
     * A user try to read a document which it doesn't have read permission
286
     */
287
    public void invalidRead()
288
    {
289
        debug("\nStarting invalidRead test...");
290
        try {
291
            m.login(anotheruser, anotherpassword);
292
            String docid = readIdFromFile(DOCID);
293
            Reader r = new InputStreamReader(m.read(docid+".1"));
294
            String doc = IOUtil.getAsString(r, true);
295
            assertTrue(doc.indexOf("<error>") != -1);
296
            debug("invalidRead(): doc="+ doc);
297
        } 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
        } catch (IOException ioe) {
306
            fail("IO exception:\n" + ioe.getMessage());
307
        } catch (DocumentNotFoundException ne) {
308
            fail("DocumentNotFound exception:\n" + ne.getMessage());
309

    
310
        } catch(Exception e) {
311
            fail("Exception:\n" + e.getMessage());
312
        }
313
    }
314

    
315
    /**
316
     * Test the query() function with a known document
317
     */
318
    public void query()
319
    {
320
        debug("\nStarting query test...");
321
        try {
322
            m.login(username,password);
323
            FileReader fr = new FileReader(queryFile);
324
            Reader r = m.query(fr);
325
            String result = IOUtil.getAsString(r, true);
326
            debug("query(): Query result=\n" + result);
327
            String docid = readIdFromFile(DOCID);
328
            assertTrue(result.indexOf(docid+".1")!=-1);
329
            assertTrue(result.indexOf("<?xml")!=-1);
330
        } catch (MetacatAuthException mae) {
331
            fail("Authorization failed:\n" + mae.getMessage());
332
        } catch (MetacatInaccessibleException mie) {
333
            fail("Metacat Inaccessible:\n" + mie.getMessage());
334
        } catch (Exception e) {
335
            fail("General exception:\n" + e.getMessage());
336
        }
337
    }
338
    /**
339
     * Test the query() function with a known document
340
     */
341
    public void queryWithQformat()
342
    {
343
        debug("\nStarting queryWithQformat test...");
344
        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
            debug("queryWithQformat(): Query result=\n" + result);
351
            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

    
363
    /**
364
     * Test the insert() function with a known document
365
     */
366
    public void insert()
367
    {
368
        debug("\nStarting insert test...");
369
        try {
370
            String identifier = newdocid + ".1";
371
            //write newdocid into file for persistance
372
            writeIdToFile(DOCID, newdocid);
373
            m.login(username, password);
374
            String response = m.insert(identifier,
375
                    new StringReader(testdocument), null);
376
            assertTrue(response.indexOf("<success>") != -1);
377
            assertTrue(response.indexOf(identifier) != -1);
378
            debug("insert(): response=" + response);
379

    
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
            assertTrue(1 == 1);
386
            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
    
394
    /**
395
     * Test to get access control part of a document
396
     */
397
    public void getAccessControl() {
398
        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
    }
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

    
460
    /**
461
     * 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
     */
466
    public void upload()
467
    {
468
        debug("\nStarting upload test...");
469
        try {
470
            newdocid = generateDocumentId();
471
            String identifier = newdocid + ".1";
472
            writeIdToFile(DATAID, newdocid);
473
            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
            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
            debug("upload(): response=" + response);
484
            //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

    
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
    
511

    
512

    
513
    /**
514
     * Test the upload() function by passing an InputStream
515
     */
516
    public void upload_stream()
517
    {
518
        debug("\nStarting upload_stream test...");
519
        try {
520
            newdocid = generateDocumentId();
521
            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
            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
           debug("upload_stream(): response=" + response);
538

    
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
    
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

    
568
            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
    /**
594
     * 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
        debug("\nStarting invalidUpdate test...");
600
        try {
601
        	String docid = readIdFromFile(DOCID);
602
            String identifier = docid + ".2";
603
            m.login(anotheruser, anotherpassword);
604
            String response = m.update(identifier,
605
                    new StringReader(testdocument), null);
606
            assertTrue(response.indexOf("<success>") == -1);
607

    
608
        } 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

    
621
    /**
622
     * Test the update() function with a known document
623
     */
624
    public void update()
625
    {
626
        debug("\nStarting update test...");
627
        try {
628
        	String docid = readIdFromFile(DOCID);
629
            String identifier = docid + ".2";
630
            m.login(username, password);
631
            String response = m.update(identifier,
632
                    new StringReader(testdocument), null);
633
            assertTrue(response.indexOf("<success>") != -1);
634
            assertTrue(response.indexOf(identifier) != -1);
635
            debug("update(): response=" + response);
636

    
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

    
650
    /**
651
     * A user try delete a document which it doesn't have permission
652
     */
653
    public void invalidDelete()
654
    {
655
        debug("\nStarting invalidDelete test...");
656
        try {
657
            String identifier = newdocid + ".2";
658
            m.login(anotheruser, anotherpassword);
659
            String response = m.delete(identifier);
660
            assertTrue(response.indexOf("<success>") == -1);
661
            debug("invalidDelete(): response=" + response);
662

    
663
        } 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

    
676
    /**
677
     * Test the delete() function with a known document
678
     */
679
    public void delete()
680
    {
681
        debug("\nStarting delete test...");
682
        try {
683
        	Thread.sleep(10000);
684
        	String docid = readIdFromFile(DOCID);
685
            String identifier = docid + ".2";
686
            m.login(username, password);
687
            String response = m.delete(identifier);
688
            assertTrue(response.indexOf("<success>") != -1);
689
            // delete the docid persistence file.
690
            deleteFile(DOCID);
691
            deleteFile(DATAID);
692
            debug("delete(): response=" + response);
693

    
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

    
707
    /**
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
    public void inaccessibleMetacat()
713
    {
714
        debug("\nStarting inaccessibleMetacat test...");
715
        Metacat mWrong = null;
716
        try {
717
            mWrong = MetacatFactory.createMetacatConnection(wrongMetacatUrl);
718
        } catch (MetacatInaccessibleException mie) {
719
            fail("Metacat Inaccessible:\n" + mie.getMessage());
720
        }
721

    
722
        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

    
731
    /**
732
     * 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
        debug("\nStarting reuseSession test...");
739
        String oldSessionId = "";
740
        try {
741
        	debug("creating metacat connection to: " + metacatUrl);
742
            Metacat mtemp = MetacatFactory.createMetacatConnection(metacatUrl);
743
        	debug("creating metacat connection with credentials: " + username + ":" + password);
744
            String response = mtemp.login(username, password);
745
            oldSessionId = mtemp.getSessionId();
746
            debug("preparing to reuse session with oldSessionId:" + oldSessionId);
747
        } 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
            String identifier = generateDocumentId() + ".1";
756
            Metacat m2 = null;
757
            try {
758
            	debug("Creating second connection and logging out of it.");
759
                m2 = MetacatFactory.createMetacatConnection(metacatUrl);
760
                m2.login(username, password);
761
                m2.logout();
762
            } catch (MetacatInaccessibleException mie) {
763
                System.err.println("Could not connect to metacat at: " + metacatUrl 
764
                		+ " : " + mie.getMessage());
765
                fail("Metacat connection failed." + mie.getMessage());
766
            }
767
            m2.setSessionId(oldSessionId);
768
            debug("Reusing second session with session id :" + m2.getSessionId());
769
            String response = m2.insert(identifier,
770
                    new StringReader(testdocument), null);
771
            debug("Reuse second session insert response: " + response);
772
            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
     * Try to perform an action that requires a session to be valid without
786
     * having logged in first, but use an invalid session identifier.
787
     * Then insert a document, which should fail.
788
     */
789
    public void reuseInvalidSession()
790
    {
791
        debug("\nStarting resuseInvalidSession test...");
792
        String oldSessionId = "foobar";
793
        try {
794
            String identifier = generateDocumentId() + ".1";
795
            Metacat m3 = null;
796
            try {
797
                m3 = MetacatFactory.createMetacatConnection(metacatUrl);
798
                m3.logout();
799
            } catch (MetacatInaccessibleException mie) {
800
                System.err.println("Metacat is: " + metacatUrl);
801
                fail("Metacat connection failed." + mie.getMessage());
802
            }
803
            debug("reuseInvalidSession(): SessionId (m3): " + m3.getSessionId());
804
            m3.setSessionId(oldSessionId);
805
            debug("reuseInvalidSession(): SessionId(m3 after set)=" + m3.getSessionId());
806
            debug("reuseInvalidSession(): identifier=" + identifier);
807
            String response = m3.insert(identifier,
808
                    new StringReader(testdocument), null);
809
            debug("reuseInvalidSession(): response=" + response);
810
            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
            if(me.getMessage().
817
               indexOf("Permission denied for user public inser") == -1){
818
                fail("Metacat Error:\n" + me.getMessage());
819
            }
820
        } catch (Exception e) {
821
            fail("General exception:\n" + e.getMessage());
822
        }
823
    }
824
    
825
   /**
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
    * immediately following a successful insert() test, AND that the docid
829
    * inserted has the maximal numerical value.
830
    */
831
   public void getLastDocid()
832
   {
833
       debug("\nStarting getLastDocid test...");
834
       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
           
844
           debug("getLastDocid(): Scope = '"+ prefix + "', Last Id = " + lastId);
845
           
846
           //get docid from file
847
           String docid = readIdFromFile(DOCID);
848
           debug("getLastDocid(): File Id = " + docid + ".1");
849
           assertTrue(lastId.equals(docid + ".1"));
850
       } 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
    * 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
       debug("\nStarting getNewestDocRevision test...");
865
       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
           // get docid from file
875
           String docid = readIdFromFile(DOCID);
876
           int revision = m3.getNewestDocRevision(docid);
877
           debug("getNewestDocRevision(): revision=" + revision);
878
           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
   
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
        debug("\nStarting insertSpatialDocs test...");
896
        
897
    	FileReader fr = new FileReader(spatialTestFile);
898
        String spatialtestdocument = IOUtil.getAsString(fr, true);
899
        debug("insertSpatialDocs(): the eml is "+spatialtestdocument);
900
    	for (int i=0; i<TIME; i++)
901
    	{
902
	    	try {
903
	    		Thread.sleep(20000);
904
	    		newdocid = generateDocumentId();
905
	            String identifier = newdocid + ".1";
906
	            debug("insertSpatialDocs(): the docid is "+identifier);
907
	            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
	            Thread.sleep(20000);
913
	            identifier = newdocid +".2";
914
	            response = m.update(identifier,
915
	                    new StringReader(spatialtestdocument), null);
916
	            assertTrue(response.indexOf("<success>") != -1);
917
	            Thread.sleep(20000);
918
	            String response2 = m.delete(identifier);
919
	            assertTrue(response2.indexOf("<success>") != -1);
920
	            debug("insertSpatialDocs(): response=" + response);
921
	
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
    
937
    /*
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
}
    (1-1/1)