Project

General

Profile

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