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: 2011-07-20 14:48:08 -0700 (Wed, 20 Jul 2011) $'
10
 * '$Revision: 6360 $'
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.properties.PropertyService;
31
import edu.ucsb.nceas.utilities.HttpMessage;
32
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
33

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

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

    
41

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

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

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

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

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

    
85
	}
86

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

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

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

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

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

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

    
135
		suite.addTest(new MetaCatServletTest("testLogOut"));
136

    
137
		return suite;
138
	}
139

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

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

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

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

    
190
		debug("Logging into lter: " + user + " : " + passwd);
191
		assertTrue(logIn(user, passwd));
192

    
193
	}
194

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

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

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

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

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

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

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

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

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

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

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

    
334
	}
335

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

    
351
	}
352

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

    
368
	}
369

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

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

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

    
411
	}
412

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

    
421
	}
422

    
423
	/**
424
	 * Method to hanld login action
425
	 * 
426
	 * @param usrerName,
427
	 *            the DN name of the test method
428
	 * @param passWord,
429
	 *            the passwd of the user
430
	 */
431

    
432
	public boolean logIn(String userName, String passWord) {
433
		Properties prop = new Properties();
434
		prop.put("action", "login");
435
		prop.put("qformat", "xml");
436
		prop.put("username", userName);
437
		prop.put("password", passWord);
438

    
439
		// Now contact metacat
440
		String response = getMetacatString(prop);
441
		debug("Login Message: " + response);
442
		boolean connected = false;
443
		if (response != null && response.indexOf("<login>") != -1) {
444
			connected = true;
445
		} else {
446

    
447
			connected = false;
448
		}
449

    
450
		return connected;
451
	}
452

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

    
462
	public boolean handleLogOut() {
463
		boolean disConnected = false;
464
		Properties prop = new Properties();
465
		prop.put("action", "logout");
466
		prop.put("qformat", "xml");
467

    
468
		String response = getMetacatString(prop);
469
		debug("Logout Message: " + response);
470
		HttpMessage.setCookie(null);
471

    
472
		if (response.indexOf("<logout>") != -1) {
473
			disConnected = true;
474
		} else {
475
			disConnected = false;
476
		}
477

    
478
		return disConnected;
479
	}
480

    
481
	/**
482
	 * Method to hanld read both xml and data file
483
	 * 
484
	 * @param docid,
485
	 *            the docid of the document want to read
486
	 * @param qformat,
487
	 *            the format of document user want to get
488
	 */
489
	public boolean handleReadAction(String docid, String qformat) {
490
		Properties prop = new Properties();
491
		String message = "";
492
		prop.put("action", "read");
493
		prop.put("qformat", qformat);
494
		prop.put("docid", docid);
495

    
496
		message = getMetacatString(prop);
497
		message = message.trim();
498
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {// there
499
																						// was
500
																						// an
501
																						// error
502

    
503
			return false;
504
		} else {// successfully
505
			return true;
506
		}
507

    
508
	}
509

    
510
	/**
511
	 * Method to hanld inset or update xml document
512
	 * 
513
	 * @param xmlDocument,
514
	 *            the content of xml qformat
515
	 * @param docid,
516
	 *            the docid of the document
517
	 * @param action,
518
	 *            insert or update
519
	 */
520
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
521

    
522
	{ // -attempt to write file to metacat
523
		String access = "no";
524
		StringBuffer fileText = new StringBuffer();
525
		StringBuffer messageBuf = new StringBuffer();
526
		String accessFileId = null;
527
		Properties prop = new Properties();
528
		prop.put("action", action);
529
		prop.put("public", access); // This is the old way of controlling access
530
		prop.put("doctext", xmlDocument);
531
		prop.put("docid", docid);
532

    
533
		String message = getMetacatString(prop);
534
		debug("Insert or Update Message: " + message);
535
		if (message.indexOf("<error>") != -1) {// there was an error
536

    
537
			return false;
538
		} else if (message.indexOf("<success>") != -1) {// the operation worked
539
			// write the file to the cache and return the file object
540
			return true;
541

    
542
		} else {// something weird happened.
543
			return false;
544
		}
545

    
546
	}
547

    
548
	public boolean handleDeleteFile(String name) {
549

    
550
		Properties prop = new Properties();
551
		prop.put("action", "delete");
552
		prop.put("docid", name);
553

    
554
		String message = getMetacatString(prop);
555
		debug("Delete Message: " + message);
556
		if (message.indexOf("<error>") != -1) {// there was an error
557

    
558
			return false;
559
		} else if (message.indexOf("<success>") != -1) {// the operation worked
560
			// write the file to the cache and return the file object
561
			return true;
562

    
563
		} else {// something weird happened.
564
			return false;
565
		}
566
	}
567

    
568
	public String getMetacatString(Properties prop) {
569
		String response = null;
570

    
571
		// Now contact metacat and send the request
572
		try {
573
			InputStreamReader returnStream = new InputStreamReader(
574
					getMetacatInputStream(prop));
575
			StringWriter sw = new StringWriter();
576
			int len;
577
			char[] characters = new char[512];
578
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
579
				sw.write(characters, 0, len);
580
			}
581
			returnStream.close();
582
			response = sw.toString();
583
			sw.close();
584
		} catch (Exception e) {
585
			return null;
586
		}
587

    
588
		return response;
589
	}
590

    
591
	/**
592
	 * Send a request to Metacat
593
	 * 
594
	 * @param prop
595
	 *            the properties to be sent to Metacat
596
	 * @return InputStream as returned by Metacat
597
	 */
598
	public InputStream getMetacatInputStream(Properties prop) {
599
		InputStream returnStream = null;
600
		// Now contact metacat and send the request
601
		try {
602

    
603
			URL url = new URL(metacatURL);
604
			HttpMessage msg = new HttpMessage(url);
605
			returnStream = msg.sendPostMessage(prop);
606
			return returnStream;
607
		} catch (Exception e) {
608
			e.printStackTrace(System.err);
609

    
610
		}
611
		return returnStream;
612

    
613
	}
614

    
615
}
(10-10/24)