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: leinfelder $'
9
 *     '$Date: 2013-07-03 10:13:46 -0700 (Wed, 03 Jul 2013) $'
10
 * '$Revision: 7843 $'
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
		return suite;
141
	}
142

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

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

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

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

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

    
196
	}
197

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

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

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

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

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

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

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

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

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

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

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

    
337
	}
338

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

    
354
	}
355

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

    
371
	}
372

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

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

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

    
414
	}
415

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

    
424
	}
425
	
426
	public void testReindexFail() {
427

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

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

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

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

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

    
473
			connected = false;
474
		}
475

    
476
		return connected;
477
	}
478

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

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

    
494
		String response = getMetacatString(prop);
495
		debug("Logout Message: " + response);
496
		HttpMessage.setCookie(null);
497

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

    
504
		return disConnected;
505
	}
506

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

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

    
529
			return false;
530
		} else {// successfully
531
			return true;
532
		}
533

    
534
	}
535

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

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

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

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

    
568
		} else {// something weird happened.
569
			return false;
570
		}
571

    
572
	}
573

    
574
	public boolean handleDeleteFile(String name) {
575

    
576
		Properties prop = new Properties();
577
		prop.put("action", "delete");
578
		prop.put("docid", name);
579

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

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

    
589
		} else {// something weird happened.
590
			return false;
591
		}
592
	}
593

    
594
	public String getMetacatString(Properties prop) {
595
		String response = null;
596

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

    
614
		return response;
615
	}
616

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

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

    
636
		}
637
		return returnStream;
638

    
639
	}
640

    
641
}
(10-10/24)