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