Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 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
 *    Authors: Jing Tao
7
 *
8
 *   '$Author: jones $'
9
 *     '$Date: 2011-05-19 19:06:08 -0700 (Thu, 19 May 2011) $'
10
 * '$Revision: 6094 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

    
27
package edu.ucsb.nceas.metacattest;
28

    
29
import edu.ucsb.nceas.MCTestCase;
30
import edu.ucsb.nceas.metacat.dataone.CrudServiceTest;
31
import edu.ucsb.nceas.metacat.properties.PropertyService;
32
import edu.ucsb.nceas.utilities.HttpMessage;
33
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
34

    
35
import junit.framework.Test;
36
import junit.framework.TestSuite;
37

    
38
import java.io.*;
39
import java.net.*;
40
import java.util.*;
41

    
42
import org.dataone.service.types.AuthToken;
43
import org.dataone.service.types.Identifier;
44

    
45
/**
46
 * A JUnit test for testing Step class processing
47
 */
48
public class MetaCatServletTest extends MCTestCase {
49
	private static String metacatURL;
50
	private String serialNumber;
51

    
52
	/* Initialize properties */
53
	static {
54
		try {
55
			metacatURL = PropertyService.getProperty("test.metacatUrl");
56
		} catch (PropertyNotFoundException pnfe) {
57
			System.err.println("Could not get property in static block: "
58
					+ pnfe.getMessage());
59
		}
60
	}
61

    
62
	/**
63
	 * Constructor to build the test
64
	 * 
65
	 * @param name
66
	 *            the name of the test method
67
	 */
68
	public MetaCatServletTest(String name) {
69
		super(name);
70
	}
71

    
72
	/**
73
	 * Constructor to build the test
74
	 * 
75
	 * @param name
76
	 *            the name of the test method
77
	 */
78
	public MetaCatServletTest(String name, String serial) {
79
		super(name);
80
		serialNumber = serial;
81
	}
82

    
83
	/**
84
	 * Establish a testing framework by initializing appropriate objects
85
	 */
86
	public void setUp() {
87

    
88
	}
89

    
90
	/**
91
	 * Release any objects after tests are complete
92
	 */
93
	public void tearDown() {
94
	}
95

    
96
	/**
97
	 * Create a suite of tests to be run together
98
	 */
99
	public static Test suite() {
100
		double number = 0;
101
		String serial = null;
102

    
103
		TestSuite suite = new TestSuite();
104
		suite.addTest(new MetaCatServletTest("initialize"));
105
		suite.addTest(new MetaCatServletTest("testLterReferralLogin"));
106
		suite.addTest(new MetaCatServletTest("testLterReferralLoginFail"));
107
		// the pisco referral isn't working in test environment, so commenting out the tests
108
		//		suite.addTest(new MetaCatServletTest("testPiscoReferralLogin"));
109
		//      suite.addTest(new MetaCatServletTest("testPiscoReferralLoginFail"));
110
		suite.addTest(new MetaCatServletTest("testNCEASLoginFail"));
111
		// Should put a login successfully at the end of login test
112
		// So insert or update can have cookie.
113
		suite.addTest(new MetaCatServletTest("testNCEASLogin"));
114

    
115
		// create random number for docid, so it can void repeat
116
		number = Math.random() * 100000;
117
		serial = Integer.toString(((new Double(number)).intValue()));
118
		debug("serial: " + serial);
119
		suite.addTest(new MetaCatServletTest("testInsertXMLDocument", serial));
120
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentXMLFormat", serial));
121
		suite.addTest(new MetaCatServletTest("testUpdateXMLDocument", serial));
122
    
123
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentHTMLFormat", serial));
124
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentZipFormat", serial));
125
    
126
		suite.addTest(new MetaCatServletTest("testDeleteXMLDocument", serial));
127
		
128
		// test delete using GUID
129
		number = Math.random() * 100000;
130
		serial = Integer.toString(((new Double(number)).intValue()));
131
		suite.addTest(new MetaCatServletTest("testDeleteDocumentByGUID", serial));
132

    
133
		// insert invalid xml document
134
		number = Math.random() * 100000;
135
		serial = Integer.toString(((new Double(number)).intValue()));
136
		suite.addTest(new MetaCatServletTest("testInsertInvalidateXMLDocument", serial));
137
		// insert non well formed document
138
		number = Math.random() * 100000;
139
		serial = Integer.toString(((new Double(number)).intValue()));
140
		suite
141
				.addTest(new MetaCatServletTest("testInsertNonWellFormedXMLDocument",
142
						serial));
143
    
144
		suite.addTest(new MetaCatServletTest("testLogOut"));
145

    
146
		return suite;
147
	}
148

    
149
	/**
150
	 * Run an initial test that always passes to check that the test harness is
151
	 * working.
152
	 */
153
	public void initialize() {
154
		assertTrue(1 == 1);
155
	}
156

    
157
	/**
158
	 * Test the login to neceas succesfully
159
	 */
160
    public void testNCEASLogin() {
161
        debug("\nRunning: testNCEASLogin test");
162
        try {
163
            String user = PropertyService.getProperty("test.mcUser");
164
            String passwd = PropertyService.getProperty("test.mcPassword");
165
            assertTrue(logIn(user, passwd));
166
        } catch (PropertyNotFoundException pnfe) {
167
            fail("Could not find property: " + pnfe.getMessage());
168
        }
169
    }
170

    
171
	/**
172
	 * Test the login to neceas failed
173
	 */
174
	public void testNCEASLoginFail() {
175
		debug("\nRunning: testNCEASLoginFail test");
176
        try {
177
            String user = PropertyService.getProperty("test.mcUser");
178
            String passwd = "BogusPasswordShouldFail";
179
            assertTrue(!logIn(user, passwd));
180
        } catch (PropertyNotFoundException pnfe) {
181
            fail("Could not find property: " + pnfe.getMessage());
182
        }
183
	}
184

    
185
	/**
186
	 * Test the login to lter succesfully
187
	 */
188
	public void testLterReferralLogin() {
189
		debug("\nRunning: testLterReferralLogin test");
190
		String user = null;
191
		String passwd = null;
192
		try {
193
			user = PropertyService.getProperty("test.lterUser");
194
			passwd = PropertyService.getProperty("test.lterPassword");
195
		} catch (PropertyNotFoundException pnfe) {
196
			fail("Could not find property: " + pnfe.getMessage());
197
		}
198

    
199
		debug("Logging into lter: " + user + " : " + passwd);
200
		assertTrue(logIn(user, passwd));
201

    
202
	}
203

    
204
	/**
205
	 * Test the login to lter failed
206
	 */
207
	public void testLterReferralLoginFail() {
208
		debug("\nRunning: testLterReferralLoginFail test");
209
		String user = "uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
210
		String passwd = "qVyGpveb";
211
		assertTrue(!logIn(user, passwd));
212
		// assertTrue( withProtocol.getProtocol().equals("http"));
213
	}
214

    
215
	/**
216
	 * Test the login to pisco succesfully
217
	 */
218
	public void testPiscoReferralLogin() {
219
		debug("\nRunning: testPiscoReferralLogin test");
220
		String user = null;
221
		String passwd = null;
222
		try {
223
			user = PropertyService.getProperty("test.piscoUser");
224
			passwd = PropertyService.getProperty("test.piscoPassword");
225
		} catch (PropertyNotFoundException pnfe) {
226
			fail("Could not find property: " + pnfe.getMessage());
227
		}
228
		debug("logging in pisco user: " + user + ":" + passwd);
229
		assertTrue(logIn(user, passwd));
230
		// assertTrue( withProtocol.getProtocol().equals("http"));
231
	}
232

    
233
	/**
234
	 * Test the login to pisco failed
235
	 */
236
	public void testPiscoReferralLoginFail() {
237
		debug("\nRunning: testPiscoReferralLoginFail test");
238
		String user = "uid=tao,o=PISCO,dc=ecoinformatics,dc=org";
239
		String passwd = "hello";
240
		assertTrue(!logIn(user, passwd));
241
		// assertTrue( withProtocol.getProtocol().equals("http"));
242
	}
243

    
244
	/**
245
	 * Test insert a xml document successfully
246
	 */
247
    public void testInsertXMLDocument() {
248
        debug("\nRunning: testInsertXMLDocument test");
249
        String name = null;
250
        try {
251
            String user = PropertyService.getProperty("test.mcUser");
252
            String passwd = PropertyService.getProperty("test.mcPassword");
253

    
254
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
255
                    + "1";
256
            debug("insert docid: " + name);
257
            String content = "<?xml version=\"1.0\"?>" + "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
258
                    + "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb.edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
259
                    + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>" + "<principal>" + user
260
                    + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
261
                    + "<permission>read</permission>" + "</allow>" + "</acl>";
262
            debug("xml document: " + content);
263
            assertTrue(handleXMLDocument(content, name, "insert"));
264
        } catch (PropertyNotFoundException pnfe) {
265
            fail("Could not find property: " + pnfe.getMessage());
266
        }
267
    }
268

    
269
	/**
270
	 * Test insert a invalidate xml document successfully In the String, there
271
	 * is no <!Doctype ... Public/System/>
272
	 */
273
    public void testInsertInvalidateXMLDocument() {
274
        debug("\nRunning: testInsertInvalidateXMLDocument test");
275
        String name = null;
276
        try {
277
            String user = PropertyService.getProperty("test.mcUser");
278
            String passwd = PropertyService.getProperty("test.mcPassword");
279

    
280
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
281
                    + "1";
282
            debug("insert docid: " + name);
283
            String content = "<?xml version=\"1.0\"?>" + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>"
284
                    + "<principal>" + user + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
285
                    + "<permission>read</permission>" + "</allow>" + "</acl>";
286
            debug("xml document: " + content);
287
            assertTrue(handleXMLDocument(content, name, "insert"));
288
        } catch (PropertyNotFoundException pnfe) {
289
            fail("Could not find property: " + pnfe.getMessage());
290
        }
291
    }
292

    
293
	/**
294
	 * Test insert a non well-formed xml document successfully There is no
295
	 * </acl> in this string
296
	 */
297
    public void testInsertNonWellFormedXMLDocument() {
298
        debug("\nRunning: testInsertNonWellFormedXMLDocument test");
299
        String name = null;
300
        try {
301
            String user = PropertyService.getProperty("test.mcUser");
302
            String passwd = PropertyService.getProperty("test.mcPassword");
303

    
304
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
305
                    + "1";
306
            debug("insert non well-formed docid: " + name);
307
            String content = "<?xml version=\"1.0\"?>" + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>"
308
                    + "<principal>" + user + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
309
                    + "<permission>read</permission>" + "</allow>";
310

    
311
            debug("xml document: " + content);
312
            assertTrue(!handleXMLDocument(content, name, "insert"));
313
        } catch (PropertyNotFoundException pnfe) {
314
            fail("Could not find property: " + pnfe.getMessage());
315
        }
316
    }
317

    
318
	/**
319
	 * Test read a xml document in xml format successfully
320
	 */
321
	public void testReadXMLDocumentXMLFormat() {
322
		debug("\nRunning: testReadXMLDocumentXMLFormat test");
323
		String name = null;
324
		try {
325
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
326
					+ serialNumber
327
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
328
		} catch (PropertyNotFoundException pnfe) {
329
			fail("Could not find property: " + pnfe.getMessage());
330
		}
331
		assertTrue(handleReadAction(name, "xml"));
332

    
333
	}
334

    
335
	/**
336
	 * Test read a xml document in html format successfully
337
	 */
338
	public void testReadXMLDocumentHTMLFormat() {
339
		debug("\nRunning: testReadXMLDocumentHTMLFormat test");
340
		String name = null;
341
		try {
342
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
343
					+ serialNumber
344
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
345
		} catch (PropertyNotFoundException pnfe) {
346
			fail("Could not find property: " + pnfe.getMessage());
347
		}
348
		assertTrue(handleReadAction(name, "html"));
349

    
350
	}
351

    
352
	/**
353
	 * Test read a xml document in zip format successfully
354
	 */
355
	public void testReadXMLDocumentZipFormat() {
356
		debug("\nRunning: testReadXMLDocumentZipFormat test");
357
		String name = null;
358
		try {
359
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
360
					+ serialNumber
361
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
362
		} catch (PropertyNotFoundException pnfe) {
363
			fail("Could not find property: " + pnfe.getMessage());
364
		}
365
		assertTrue(handleReadAction(name, "zip"));
366

    
367
	}
368

    
369
	/**
370
	 * Test insert a xml document successfully
371
	 */
372
    public void testUpdateXMLDocument() {
373
        debug("\nRunning: testUpdateXMLDocument test");
374
        String name = null;
375
        try {
376
            String user = PropertyService.getProperty("test.mcUser");
377
            String passwd = PropertyService.getProperty("test.mcPassword");
378

    
379
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
380
                    + "2";
381
            debug("update docid: " + name);
382
            String content = "<?xml version=\"1.0\"?>" + "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
383
                    + "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb." + "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
384
                    + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>" + "<principal>" + user
385
                    + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
386
                    + "<permission>read</permission>" + "</allow>" + "</acl>";
387
            debug("xml document: " + content);
388
            assertTrue(handleXMLDocument(content, name, "update"));
389
        } catch (PropertyNotFoundException pnfe) {
390
            fail("Could not find property: " + pnfe.getMessage());
391
        }
392
    }
393

    
394
	/**
395
	 * Test delete a xml document successfully
396
	 */
397
	public void testDeleteXMLDocument() {
398
		debug("\nRunning: testDeleteXMLDocument test");
399
		String name = null;
400
		try {
401
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
402
					+ serialNumber
403
					+ PropertyService.getProperty("document.accNumSeparator") + "2";
404
		} catch (PropertyNotFoundException pnfe) {
405
			fail("Could not find property: " + pnfe.getMessage());
406
		}
407
		debug("delete docid: " + name);
408
		assertTrue(handleDeleteFile(name));
409

    
410
	}
411

    
412
    /**
413
     * Test to delete a document by GUID (not docid).  This exercises 
414
     * MetacatServlet.handleDeleteAction()'s handling of GUIDs.
415
     */
416
    public void testDeleteDocumentByGUID() {
417
        debug("\nRunning: testDeleteDocumentByGUID test");
418

    
419
        try {
420
            String user = PropertyService.getProperty("test.mcUser");
421
            String passwd = PropertyService.getProperty("test.mcPassword");
422
            
423
            CrudServiceTest crudServiceTest = new CrudServiceTest("testDeleteDocumentByGUID");
424
            String guid = "";
425
            AuthToken token = null;
426
            String result = "";
427
            // create a document via the CRUD service to get a GUID
428
            try {
429
                token = crudServiceTest.getToken(user, passwd);
430
                String testDocument = crudServiceTest.getTestDoc();
431
                Identifier identifier = crudServiceTest.createDoc(token, testDocument);
432
                guid = identifier.getValue();
433
            } catch (Exception e) {
434
                fail("Could not create test document to delete: " + e.getMessage());
435
            }
436

    
437
            // delete the document via the Metacat servlet with the GUID
438
            try {
439
                Properties props = new Properties();
440
                props.put("action", "delete");
441
                props.put("docid", guid);
442
                props.put("sessionid", token.getToken());
443
                debug("Trying to delete by GUID: " + guid);
444
                result = getMetacatString(props);
445
            } catch (Exception e) {
446
                fail("Couldn't delete GUID: " + guid);
447
            }
448
            assertTrue(result.indexOf("<success>") > 0);
449
        } catch (PropertyNotFoundException pnfe) {
450
            fail("Could not find property: " + pnfe.getMessage());
451
        }
452
    }
453
    
454
	/**
455
	 * Test logout action
456
	 */
457
	public void testLogOut() {
458
		debug("\nRunning: testLogOut test");
459
		assertTrue(handleLogOut());
460

    
461
	}
462

    
463
	/**
464
	 * Method to hanld login action
465
	 * 
466
	 * @param usrerName,
467
	 *            the DN name of the test method
468
	 * @param passWord,
469
	 *            the passwd of the user
470
	 */
471

    
472
	public boolean logIn(String userName, String passWord) {
473
		Properties prop = new Properties();
474
		prop.put("action", "login");
475
		prop.put("qformat", "xml");
476
		prop.put("username", userName);
477
		prop.put("password", passWord);
478

    
479
		// Now contact metacat
480
		String response = getMetacatString(prop);
481
		debug("Login Message: " + response);
482
		boolean connected = false;
483
		if (response.indexOf("<login>") != -1) {
484
			connected = true;
485
		} else {
486

    
487
			connected = false;
488
		}
489

    
490
		return connected;
491
	}
492

    
493
	/**
494
	 * Method to hanld logout action
495
	 * 
496
	 * @param usrerName,
497
	 *            the DN name of the test method
498
	 * @param passWord,
499
	 *            the passwd of the user
500
	 */
501

    
502
	public boolean handleLogOut() {
503
		boolean disConnected = false;
504
		Properties prop = new Properties();
505
		prop.put("action", "logout");
506
		prop.put("qformat", "xml");
507

    
508
		String response = getMetacatString(prop);
509
		debug("Logout Message: " + response);
510
		HttpMessage.setCookie(null);
511

    
512
		if (response.indexOf("<logout>") != -1) {
513
			disConnected = true;
514
		} else {
515
			disConnected = false;
516
		}
517

    
518
		return disConnected;
519
	}
520

    
521
	/**
522
	 * Method to hanld read both xml and data file
523
	 * 
524
	 * @param docid,
525
	 *            the docid of the document want to read
526
	 * @param qformat,
527
	 *            the format of document user want to get
528
	 */
529
	public boolean handleReadAction(String docid, String qformat) {
530
		Properties prop = new Properties();
531
		String message = "";
532
		prop.put("action", "read");
533
		prop.put("qformat", qformat);
534
		prop.put("docid", docid);
535

    
536
		message = getMetacatString(prop);
537
		message = message.trim();
538
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {// there
539
																						// was
540
																						// an
541
																						// error
542

    
543
			return false;
544
		} else {// successfully
545
			return true;
546
		}
547

    
548
	}
549

    
550
	/**
551
	 * Method to hanld inset or update xml document
552
	 * 
553
	 * @param xmlDocument,
554
	 *            the content of xml qformat
555
	 * @param docid,
556
	 *            the docid of the document
557
	 * @param action,
558
	 *            insert or update
559
	 */
560
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
561

    
562
	{ // -attempt to write file to metacat
563
		String access = "no";
564
		StringBuffer fileText = new StringBuffer();
565
		StringBuffer messageBuf = new StringBuffer();
566
		String accessFileId = null;
567
		Properties prop = new Properties();
568
		prop.put("action", action);
569
		prop.put("public", access); // This is the old way of controlling access
570
		prop.put("doctext", xmlDocument);
571
		prop.put("docid", docid);
572

    
573
		String message = getMetacatString(prop);
574
		debug("Insert or Update Message: " + message);
575
		if (message.indexOf("<error>") != -1) {// there was an error
576

    
577
			return false;
578
		} else if (message.indexOf("<success>") != -1) {// the operation worked
579
			// write the file to the cache and return the file object
580
			return true;
581

    
582
		} else {// something weird happened.
583
			return false;
584
		}
585

    
586
	}
587

    
588
	public boolean handleDeleteFile(String name) {
589

    
590
		Properties prop = new Properties();
591
		prop.put("action", "delete");
592
		prop.put("docid", name);
593

    
594
		String message = getMetacatString(prop);
595
		debug("Delete Message: " + message);
596
		if (message.indexOf("<error>") != -1) {// there was an error
597

    
598
			return false;
599
		} else if (message.indexOf("<success>") != -1) {// the operation worked
600
			// write the file to the cache and return the file object
601
			return true;
602

    
603
		} else {// something weird happened.
604
			return false;
605
		}
606
	}
607

    
608
	public String getMetacatString(Properties prop) {
609
		String response = null;
610

    
611
		// Now contact metacat and send the request
612
		try {
613
			InputStreamReader returnStream = new InputStreamReader(
614
					getMetacatInputStream(prop));
615
			StringWriter sw = new StringWriter();
616
			int len;
617
			char[] characters = new char[512];
618
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
619
				sw.write(characters, 0, len);
620
			}
621
			returnStream.close();
622
			response = sw.toString();
623
			sw.close();
624
		} catch (Exception e) {
625
			return null;
626
		}
627

    
628
		return response;
629
	}
630

    
631
	/**
632
	 * Send a request to Metacat
633
	 * 
634
	 * @param prop
635
	 *            the properties to be sent to Metacat
636
	 * @return InputStream as returned by Metacat
637
	 */
638
	public InputStream getMetacatInputStream(Properties prop) {
639
		InputStream returnStream = null;
640
		// Now contact metacat and send the request
641
		try {
642

    
643
			URL url = new URL(metacatURL);
644
			HttpMessage msg = new HttpMessage(url);
645
			returnStream = msg.sendPostMessage(prop);
646
			return returnStream;
647
		} catch (Exception e) {
648
			e.printStackTrace(System.err);
649

    
650
		}
651
		return returnStream;
652

    
653
	}
654

    
655
}
(10-10/24)