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: tao $'
9
 *     '$Date: 2014-03-04 10:22:31 -0800 (Tue, 04 Mar 2014) $'
10
 * '$Revision: 8696 $'
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.IdentifierManager;
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

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

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

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

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

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

    
86
	}
87

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

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

    
101
		TestSuite suite = new TestSuite();
102
		suite.addTest(new MetaCatServletTest("initialize"));
103
		suite.addTest(new MetaCatServletTest("testLterReferralLogin"));
104
		suite.addTest(new MetaCatServletTest("testLterReferralLoginFail"));
105
		suite.addTest(new MetaCatServletTest("testOtherReferralLogin"));
106
		suite.addTest(new MetaCatServletTest("testOtherReferralLoginFail"));
107
		suite.addTest(new MetaCatServletTest("testNCEASLoginFail"));
108
		// Should put a login successfully at the end of login test
109
		// So insert or update can have cookie.
110
		suite.addTest(new MetaCatServletTest("testNCEASLogin"));
111

    
112
		// create random number for docid, so it can void repeat
113
		number = Math.random() * 100000;
114
		serial = Integer.toString(((new Double(number)).intValue()));
115
		debug("serial: " + serial);
116
		suite.addTest(new MetaCatServletTest("testInsertXMLDocument", serial));
117
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentXMLFormat", serial));
118
		suite.addTest(new MetaCatServletTest("testUpdateXMLDocument", serial));
119

    
120
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentHTMLFormat", serial));
121
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentZipFormat", serial));
122

    
123
		suite.addTest(new MetaCatServletTest("testDeleteXMLDocument", serial));
124
	
125
		// insert invalid xml document
126
		number = Math.random() * 100000;
127
		serial = Integer.toString(((new Double(number)).intValue()));
128
		suite.addTest(new MetaCatServletTest("testInsertInvalidateXMLDocument", serial));
129
		// insert non well formed document
130
		number = Math.random() * 100000;
131
		serial = Integer.toString(((new Double(number)).intValue()));
132
		suite
133
				.addTest(new MetaCatServletTest("testInsertNonWellFormedXMLDocument",
134
						serial));
135

    
136
		suite.addTest(new MetaCatServletTest("testLogOut"));
137
		
138
		suite.addTest(new MetaCatServletTest("testReindexFail"));
139
		
140
		
141
		return suite;
142
	}
143

    
144
	/**
145
	 * Run an initial test that always passes to check that the test harness is
146
	 * working.
147
	 */
148
	public void initialize() {
149
		assertTrue(1 == 1);
150
	}
151

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

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

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

    
194
		debug("Logging into lter: " + user + " : " + passwd);
195
		assertTrue(logIn(user, passwd));
196

    
197
	}
198

    
199
	/**
200
	 * Test the login to lter failed
201
	 */
202
	public void testLterReferralLoginFail() {
203
		debug("\nRunning: testLterReferralLoginFail test");
204
		String user = null;
205
    String passwd = "wrong";
206
    try {
207
      user = PropertyService.getProperty("test.lterUser");
208
    } catch (PropertyNotFoundException pnfe) {
209
      fail("Could not find property: " + pnfe.getMessage());
210
    }
211
		assertTrue(!logIn(user, passwd));
212
		// assertTrue( withProtocol.getProtocol().equals("http"));
213
	}
214

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

    
233
	/**
234
	 * Test the login to Other failed
235
	 */
236
	public void testOtherReferralLoginFail() {
237
		debug("\nRunning: testOtherReferralLoginFail test");
238
		String user = null;
239
    String passwd = "wrong";
240
    try {
241
      user = PropertyService.getProperty("test.referralUser");
242
    } catch (PropertyNotFoundException pnfe) {
243
      fail("Could not find property: " + pnfe.getMessage());
244
    }
245
		assertTrue(!logIn(user, passwd));
246
		// assertTrue( withProtocol.getProtocol().equals("http"));
247
	}
248
	
249

    
250

    
251
	/**
252
	 * Test insert a xml document successfully
253
	 */
254
    public void testInsertXMLDocument() {
255
        debug("\nRunning: testInsertXMLDocument test");
256
        String name = null;
257
        try {
258
            String user = PropertyService.getProperty("test.mcUser");
259
            String passwd = PropertyService.getProperty("test.mcPassword");
260

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

    
276
	/**
277
	 * Test insert a invalidate xml document successfully In the String, there
278
	 * is no <!Doctype ... Public/System/>
279
	 */
280
    public void testInsertInvalidateXMLDocument() {
281
        debug("\nRunning: testInsertInvalidateXMLDocument test");
282
        String name = null;
283
        try {
284
            String user = PropertyService.getProperty("test.mcUser");
285
            String passwd = PropertyService.getProperty("test.mcPassword");
286

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

    
300
	/**
301
	 * Test insert a non well-formed xml document successfully There is no
302
	 * </acl> in this string
303
	 */
304
    public void testInsertNonWellFormedXMLDocument() {
305
        debug("\nRunning: testInsertNonWellFormedXMLDocument test");
306
        String name = null;
307
        try {
308
            String user = PropertyService.getProperty("test.mcUser");
309
            String passwd = PropertyService.getProperty("test.mcPassword");
310

    
311
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
312
                    + "1";
313
            debug("insert non well-formed docid: " + name);
314
            String content = "<?xml version=\"1.0\"?>" + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>"
315
                    + "<principal>" + user + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
316
                    + "<permission>read</permission>" + "</allow>";
317

    
318
            debug("xml document: " + content);
319
            assertTrue(!handleXMLDocument(content, name, "insert"));
320
        } catch (PropertyNotFoundException pnfe) {
321
            fail("Could not find property: " + pnfe.getMessage());
322
        }
323
    }
324

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

    
340
	}
341

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

    
357
	}
358

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

    
374
	}
375

    
376
	/**
377
	 * Test insert a xml document successfully
378
	 */
379
    public void testUpdateXMLDocument() {
380
        debug("\nRunning: testUpdateXMLDocument test");
381
        String name = null;
382
        try {
383
            String user = PropertyService.getProperty("test.mcUser");
384
            String passwd = PropertyService.getProperty("test.mcPassword");
385

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

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

    
417
	}
418

    
419
    
420
	/**
421
	 * Test logout action
422
	 */
423
	public void testLogOut() {
424
		debug("\nRunning: testLogOut test");
425
		assertTrue(handleLogOut());
426

    
427
	}
428
	
429
	public void testReindexFail() {
430

    
431
		// find a pid to reindex
432
		String identifier = null;
433
		List<String> ids = IdentifierManager.getInstance().getAllSystemMetadataGUIDs();
434
		if (ids != null && !ids.isEmpty()) {
435
			identifier = ids.get(0);
436
		}
437
		Properties prop = new Properties();
438
		prop.put("action", "reindex");
439
		prop.put("pid", identifier);
440

    
441
		String message = getMetacatString(prop);
442
		debug("Reindex Message: " + message);
443
		if (message.indexOf("<error>") != -1) {// there was an error
444
			assertTrue(true);
445
		} else if (message.indexOf("<success>") != -1) {
446
			fail("Unauthenticated user should not be able to invoke this action: " + message);
447
		} else {// something weird happened.
448
			fail("There was an unexpected error reindexing pid: " + message);
449
		}
450
	}
451

    
452
	/**
453
	 * Method to hanld login action
454
	 * 
455
	 * @param usrerName,
456
	 *            the DN name of the test method
457
	 * @param passWord,
458
	 *            the passwd of the user
459
	 */
460

    
461
	public boolean logIn(String userName, String passWord) {
462
		Properties prop = new Properties();
463
		prop.put("action", "login");
464
		prop.put("qformat", "xml");
465
		prop.put("username", userName);
466
		prop.put("password", passWord);
467

    
468
		// Now contact metacat
469
		String response = getMetacatString(prop);
470
		debug("Login Message: " + response);
471
		boolean connected = false;
472
		if (response != null && response.indexOf("<login>") != -1) {
473
			connected = true;
474
		} else {
475

    
476
			connected = false;
477
		}
478

    
479
		return connected;
480
	}
481

    
482
	/**
483
	 * Method to hanld logout action
484
	 * 
485
	 * @param usrerName,
486
	 *            the DN name of the test method
487
	 * @param passWord,
488
	 *            the passwd of the user
489
	 */
490

    
491
	public boolean handleLogOut() {
492
		boolean disConnected = false;
493
		Properties prop = new Properties();
494
		prop.put("action", "logout");
495
		prop.put("qformat", "xml");
496

    
497
		String response = getMetacatString(prop);
498
		debug("Logout Message: " + response);
499
		HttpMessage.setCookie(null);
500

    
501
		if (response.indexOf("<logout>") != -1) {
502
			disConnected = true;
503
		} else {
504
			disConnected = false;
505
		}
506

    
507
		return disConnected;
508
	}
509

    
510
	/**
511
	 * Method to hanld read both xml and data file
512
	 * 
513
	 * @param docid,
514
	 *            the docid of the document want to read
515
	 * @param qformat,
516
	 *            the format of document user want to get
517
	 */
518
	public boolean handleReadAction(String docid, String qformat) {
519
		Properties prop = new Properties();
520
		String message = "";
521
		prop.put("action", "read");
522
		prop.put("qformat", qformat);
523
		prop.put("docid", docid);
524

    
525
		message = getMetacatString(prop);
526
		message = message.trim();
527
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {// there
528
																						// was
529
																						// an
530
																						// error
531

    
532
			return false;
533
		} else {// successfully
534
			return true;
535
		}
536

    
537
	}
538

    
539
	/**
540
	 * Method to hanld inset or update xml document
541
	 * 
542
	 * @param xmlDocument,
543
	 *            the content of xml qformat
544
	 * @param docid,
545
	 *            the docid of the document
546
	 * @param action,
547
	 *            insert or update
548
	 */
549
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
550

    
551
	{ // -attempt to write file to metacat
552
		String access = "no";
553
		StringBuffer fileText = new StringBuffer();
554
		StringBuffer messageBuf = new StringBuffer();
555
		String accessFileId = null;
556
		Properties prop = new Properties();
557
		prop.put("action", action);
558
		prop.put("public", access); // This is the old way of controlling access
559
		prop.put("doctext", xmlDocument);
560
		prop.put("docid", docid);
561

    
562
		String message = getMetacatString(prop);
563
		debug("Insert or Update Message: " + message);
564
		if (message.indexOf("<error>") != -1) {// there was an error
565

    
566
			return false;
567
		} else if (message.indexOf("<success>") != -1) {// the operation worked
568
			// write the file to the cache and return the file object
569
			return true;
570

    
571
		} else {// something weird happened.
572
			return false;
573
		}
574

    
575
	}
576

    
577
	public boolean handleDeleteFile(String name) {
578

    
579
		Properties prop = new Properties();
580
		prop.put("action", "delete");
581
		prop.put("docid", name);
582

    
583
		String message = getMetacatString(prop);
584
		debug("Delete Message: " + message);
585
		if (message.indexOf("<error>") != -1) {// there was an error
586

    
587
			return false;
588
		} else if (message.indexOf("<success>") != -1) {// the operation worked
589
			// write the file to the cache and return the file object
590
			return true;
591

    
592
		} else {// something weird happened.
593
			return false;
594
		}
595
	}
596

    
597
	public String getMetacatString(Properties prop) {
598
		String response = null;
599

    
600
		// Now contact metacat and send the request
601
		try {
602
			InputStreamReader returnStream = new InputStreamReader(
603
					getMetacatInputStream(prop));
604
			StringWriter sw = new StringWriter();
605
			int len;
606
			char[] characters = new char[512];
607
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
608
				sw.write(characters, 0, len);
609
			}
610
			returnStream.close();
611
			response = sw.toString();
612
			sw.close();
613
		} catch (Exception e) {
614
			return null;
615
		}
616

    
617
		return response;
618
	}
619

    
620
	/**
621
	 * Send a request to Metacat
622
	 * 
623
	 * @param prop
624
	 *            the properties to be sent to Metacat
625
	 * @return InputStream as returned by Metacat
626
	 */
627
	public InputStream getMetacatInputStream(Properties prop) {
628
		InputStream returnStream = null;
629
		// Now contact metacat and send the request
630
		try {
631

    
632
			URL url = new URL(metacatURL);
633
			HttpMessage msg = new HttpMessage(url);
634
			returnStream = msg.sendPostMessage(prop);
635
			return returnStream;
636
		} catch (Exception e) {
637
			e.printStackTrace(System.err);
638

    
639
		}
640
		return returnStream;
641

    
642
	}
643

    
644
}
(11-11/26)