Project

General

Profile

1 1114 tao
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2000 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5 3080 jones
 *    Purpose: To test the MetaCatURL class by JUnit
6
 *    Authors: Jing Tao
7 1114 tao
 *
8
 *   '$Author$'
9
 *     '$Date$'
10
 * '$Revision$'
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 1117 tao
package edu.ucsb.nceas.metacatnettest;
28 1114 tao
29 4145 daigle
import edu.ucsb.nceas.MCTestCase;
30 1114 tao
import edu.ucsb.nceas.metacat.*;
31 5035 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
32 4080 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
33 4145 daigle
34 1114 tao
import junit.framework.Test;
35
import junit.framework.TestSuite;
36
37
import java.io.*;
38
import java.net.*;
39
import java.util.*;
40
41 3169 tao
import org.apache.log4j.Logger;
42 1114 tao
43
/**
44
 * A JUnit test for testing Step class processing
45
 */
46 4145 daigle
public class MetaCatServletNetTest extends MCTestCase {
47 4080 daigle
	private static String metacatURL;
48
	static {
49 4125 daigle
		try {
50 4231 daigle
			metacatURL = PropertyService.getProperty("test.metacatUrl");
51 4080 daigle
		} catch (PropertyNotFoundException pnfe) {
52
			System.err.println("could not find metacat URL in MetacatServletNetTest: "
53
					+ pnfe.getMessage());
54
		} catch (Exception e) {
55
			System.err.println("Exception in initialize option in MetacatServletNetTest: "
56
					+ e.getMessage());
57
		}
58
	}
59 1114 tao
60 4080 daigle
	private String serialNumber;
61 1114 tao
62 4080 daigle
	/**
63
	 * Constructor to build the test
64
	 *
65
	 * @param name the name of the test method
66
	 */
67
	public MetaCatServletNetTest(String name) {
68
		super(name);
69
	}
70 1114 tao
71 4080 daigle
	/**
72
	 * Constructor to build the test
73
	 *
74
	 * @param name the name of the test method
75
	 */
76
	public MetaCatServletNetTest(String name, String serial) {
77
		super(name);
78
		serialNumber = serial;
79
	}
80 1114 tao
81 4080 daigle
	/**
82
	 * Establish a testing framework by initializing appropriate objects
83
	 */
84
	public void setUp() {
85 1114 tao
86 4080 daigle
	}
87 1114 tao
88 4080 daigle
	/**
89
	 * Release any objects after tests are complete
90
	 */
91
	public void tearDown() {
92
	}
93 3562 tao
94 4080 daigle
	/**
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 1114 tao
101 4080 daigle
		TestSuite suite = new TestSuite();
102
		suite.addTest(new MetaCatServletNetTest("initialize"));
103
		suite.addTest(new MetaCatServletNetTest("testNCEASLoginFail"));
104
		//Should put a login successfully at the end of login test
105
		//So insert or update can have cookie.
106
		suite.addTest(new MetaCatServletNetTest("testNCEASLogin"));
107 1114 tao
108 4080 daigle
		//create random number for docid, so it can void repeat
109
		number = Math.random() * 100000;
110
		serial = Integer.toString(((new Double(number)).intValue()));
111 5311 daigle
		debug("serial: " + serial);
112 4080 daigle
		suite.addTest(new MetaCatServletNetTest("testInsertXMLDocument", serial));
113
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentXMLFormat", serial));
114
		suite.addTest(new MetaCatServletNetTest("testUpdateXMLDocument", serial));
115
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentHTMLFormat", serial));
116
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentZipFormat", serial));
117 1114 tao
118 4080 daigle
		suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument", serial));
119 1114 tao
120 4080 daigle
		//insert invalid xml document
121
		number = Math.random() * 100000;
122
		serial = Integer.toString(((new Double(number)).intValue()));
123 4125 daigle
		suite.addTest(new MetaCatServletNetTest("testInsertInvalidateXMLDocument",
124 4080 daigle
						serial));
125
		//insert non well formed document
126
		number = Math.random() * 100000;
127
		serial = Integer.toString(((new Double(number)).intValue()));
128
		suite.addTest(new MetaCatServletNetTest("testInsertNonWellFormedXMLDocument",
129
				serial));
130
		//insert data file
131
		number = Math.random() * 100000;
132
		serial = Integer.toString(((new Double(number)).intValue()));
133
		suite.addTest(new MetaCatServletNetTest("testLogOut"));
134 1114 tao
135 4080 daigle
		return suite;
136
	}
137 1114 tao
138 4080 daigle
	/**
139
	 * Run an initial test that always passes to check that the test
140
	 * harness is working.
141
	 */
142
	public void initialize() {
143
		assertTrue(1 == 1);
144
	}
145 1114 tao
146 4080 daigle
	/**
147 5311 daigle
	 * Test the login to nceas succesfully
148 4080 daigle
	 */
149
	public void testNCEASLogin() {
150 5478 berkley
	    System.out.println("Testing nceas login");
151 6038 jones
	    debug("\nRunning: testNCEASLogin test");
152
        try {
153
            String user = PropertyService.getProperty("test.mcUser");
154
            String passwd = PropertyService.getProperty("test.mcPassword");
155
            assertTrue(logIn(user, passwd));
156
            //assertTrue( withProtocol.getProtocol().equals("http"));
157
        } catch (PropertyNotFoundException e) {
158
            fail(e.getMessage());
159
        }
160
161 4080 daigle
	}
162 1114 tao
163 4080 daigle
	/**
164 5311 daigle
	 * Test the login to nceas failed
165 4080 daigle
	 */
166 6038 jones
    public void testNCEASLoginFail() {
167
        debug("\nRunning: testNCEASLoginFail test");
168
        try {
169
            String user = PropertyService.getProperty("test.mcUser");
170
            System.out.println("Testing nceas login fail");
171
            String passwd = "thisPasswordIsInvalidAndShouldFail";
172
            assertTrue(!logIn(user, passwd));
173 1114 tao
174 6038 jones
        } catch (PropertyNotFoundException e) {
175
            fail(e.getMessage());
176
        }
177
    }
178 1114 tao
179 4080 daigle
	/**
180
	 * Test the login to lter failed
181
	 */
182
	public void testLterReferralLoginFail() {
183 4417 daigle
		debug("\nRunning: testLterReferralLoginFail test");
184 6038 jones
        try {
185
            String user = PropertyService.getProperty("test.lterUser");
186
            String passwd = "thisPasswordIsInvalidAndShouldFail";
187
            assertTrue(!logIn(user, passwd));
188
            //assertTrue( withProtocol.getProtocol().equals("http"));
189
        } catch (PropertyNotFoundException e) {
190
            fail(e.getMessage());
191
        }
192 4080 daigle
	}
193 1114 tao
194 4080 daigle
	/**
195
	 * Test insert a xml document successfully
196
	 */
197
	public void testInsertXMLDocument() throws PropertyNotFoundException {
198 4417 daigle
		debug("\nRunning: testInsertXMLDocument test");
199 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
200
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
201 5311 daigle
		debug("insert docid: " + name);
202 4080 daigle
		String content = "<?xml version=\"1.0\"?>"
203
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
204
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
205
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
206
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
207
				+ "</identifier>" + "<allow>"
208
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
209
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
210
				+ "<principal>public</principal>" + "<permission>read</permission>"
211
				+ "</allow>" + "</acl>";
212 5311 daigle
		debug("xml document: " + content);
213 4080 daigle
		assertTrue(handleXMLDocument(content, name, "insert"));
214
215
	}
216
217
	/**
218
	 * Test insert a invalidate xml document successfully
219
	 * In the String, there is no <!Doctype ... Public/System/>
220
	 */
221
	public void testInsertInvalidateXMLDocument() throws PropertyNotFoundException  {
222 4417 daigle
		debug("\nRunning: testInsertInvalidateXMLDocument test");
223 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
224
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
225 5311 daigle
		debug("insert docid: " + name);
226 4080 daigle
		String content = "<?xml version=\"1.0\"?>"
227
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
228
				+ "</identifier>" + "<allow>"
229
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
230
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
231
				+ "<principal>public</principal>" + "<permission>read</permission>"
232
				+ "</allow>" + "</acl>";
233 5311 daigle
		debug("xml document: " + content);
234 4080 daigle
		assertTrue(handleXMLDocument(content, name, "insert"));
235
	}
236
237
	/**
238
	 * Test insert a non well-formed xml document successfully
239
	 * There is no </acl> in this string
240
	 */
241
	public void testInsertNonWellFormedXMLDocument() throws PropertyNotFoundException  {
242 4417 daigle
		debug("\nRunning: testInsertNonWellFormedXMLDocument test");
243 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
244
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
245 5311 daigle
		debug("insert non well-formed docid: " + name);
246 4080 daigle
		String content = "<?xml version=\"1.0\"?>"
247
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
248
				+ "</identifier>" + "<allow>"
249
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
250
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
251
				+ "<principal>public</principal>" + "<permission>read</permission>"
252
				+ "</allow>";
253
254 5311 daigle
		debug("xml document: " + content);
255 4080 daigle
		assertTrue(!handleXMLDocument(content, name, "insert"));
256
	}
257
258
	/**
259
	 * Test read a xml document  in xml format successfully
260
	 */
261
	public void testReadXMLDocumentXMLFormat() throws PropertyNotFoundException  {
262 4417 daigle
		debug("\nRunning: testReadXMLDocumentXMLFormat test");
263 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
264
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
265 4080 daigle
		assertTrue(handleReadAction(name, "xml"));
266
267
	}
268
269
	/**
270
	 * Test read a xml document  in html format successfully
271
	 */
272
	public void testReadXMLDocumentHTMLFormat() throws PropertyNotFoundException {
273 4417 daigle
		debug("\nRunning: testReadXMLDocumentHTMLFormat test");
274 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
275
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
276 4080 daigle
		assertTrue(handleReadAction(name, "html"));
277
278
	}
279
280
	/**
281
	 * Test read a xml document  in zip format successfully
282
	 */
283
	public void testReadXMLDocumentZipFormat() throws PropertyNotFoundException {
284 4417 daigle
		debug("\nRunning: testReadXMLDocumentZipFormat test");
285 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
286
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
287 4080 daigle
		assertTrue(handleReadAction(name, "zip"));
288
289
	}
290
291
	/**
292
	 * Test insert a xml document successfully
293
	 */
294
	public void testUpdateXMLDocument() throws PropertyNotFoundException {
295 4417 daigle
		debug("\nRunning: testUpdateXMLDocument test");
296 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
297
				+ PropertyService.getProperty("document.accNumSeparator") + "2";
298 5311 daigle
		debug("update docid: " + name);
299 4080 daigle
		String content = "<?xml version=\"1.0\"?>"
300
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
301
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
302
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
303
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
304
				+ "</identifier>" + "<allow>"
305
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
306
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
307
				+ "<principal>public</principal>" + "<permission>read</permission>"
308
				+ "</allow>" + "</acl>";
309 5311 daigle
		debug("xml document: " + content);
310 4080 daigle
		assertTrue(handleXMLDocument(content, name, "update"));
311
312
	}
313
314
	/**
315
	 * Test insert a data file successfully
316
	 */
317
	public void testInertDataFile() throws PropertyNotFoundException {
318 4417 daigle
		debug("\nRunning: testInertDataFile test");
319 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
320
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
321 5311 daigle
		debug("insert data file docid: " + name);
322
		debug("insert data file ");
323 4080 daigle
		File hello = new File("test/jones.204.22.xml");
324
325
		assertTrue(insertDataFile(name, hello));
326
	}
327
328
	/**
329
	 * Test delete a xml document successfully
330
	 */
331
	public void testDeleteXMLDocument() throws PropertyNotFoundException {
332 4417 daigle
		debug("\nRunning: testDeleteXMLDocument test");
333 4212 daigle
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
334
				+ PropertyService.getProperty("document.accNumSeparator") + "2";
335 5311 daigle
		debug("delete docid: " + name);
336 4080 daigle
		assertTrue(handleDeleteFile(name));
337
	}
338
339
	/**
340
	 * Test logout action
341
	 */
342
	public void testLogOut() {
343 4417 daigle
		debug("\nRunning: testLogOut test");
344 4080 daigle
		assertTrue(handleLogOut());
345
346
	}
347
348
	/**
349
	 * Method to hanld login action
350
	 *
351
	 * @param usrerName, the DN name of the test method
352
	 * @param passWord, the passwd of the user
353
	 */
354
355
	public boolean logIn(String userName, String passWord) {
356
		Properties prop = new Properties();
357
		prop.put("action", "login");
358
		prop.put("qformat", "xml");
359
		prop.put("username", userName);
360
		prop.put("password", passWord);
361
362
		// Now contact metacat
363
		String response = getMetacatString(prop);
364 5311 daigle
		debug("Login Message: " + response);
365 4080 daigle
		boolean connected = false;
366
		if (response.indexOf("<login>") != -1) {
367
			connected = true;
368
		} else {
369
370
			connected = false;
371
		}
372
373
		return connected;
374
	}
375
376
	/**
377
	 * Method to hanld logout action
378
	 *
379
	 * @param usrerName, the DN name of the test method
380
	 * @param passWord, the passwd of the user
381
	 */
382
383
	public boolean handleLogOut() {
384
		boolean disConnected = false;
385
		Properties prop = new Properties();
386
		prop.put("action", "logout");
387
		prop.put("qformat", "xml");
388
389
		String response = getMetacatString(prop);
390 5311 daigle
		debug("Logout Message: " + response);
391 4080 daigle
		edu.ucsb.nceas.morpho.framework.HttpMessage.setCookie(null);
392
393
		if (response.indexOf("<logout>") != -1) {
394
			disConnected = true;
395
		} else {
396
			disConnected = false;
397
		}
398
399
		return disConnected;
400
	}
401
402
	/**
403
	 * Method to hanld read both xml and data file
404
	 *
405
	 * @param docid, the docid of the document want to read
406
	 * @param qformat, the format of document user want to get
407
	 */
408
	public boolean handleReadAction(String docid, String qformat) {
409
		Properties prop = new Properties();
410
		String message = "";
411
		prop.put("action", "read");
412
		prop.put("qformat", qformat);
413
		prop.put("docid", docid);
414
415
		message = getMetacatString(prop);
416
		message = message.trim();
417 4700 daigle
		//MetacatUtil.debugMessage("Read Message: "+message, 30);
418 4080 daigle
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {//there was an error
419
420
			return false;
421
		} else {//successfully
422
			return true;
423
		}
424
425
	}
426
427
	/**
428
	 * Method to hanld inset or update xml document
429
	 *
430
	 * @param xmlDocument, the content of xml qformat
431
	 * @param docid, the docid of the document
432
	 * @param action, insert or update
433
	 */
434
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
435
436
	{ //-attempt to write file to metacat
437
		String access = "no";
438
		StringBuffer fileText = new StringBuffer();
439
		StringBuffer messageBuf = new StringBuffer();
440
		String accessFileId = null;
441
		Properties prop = new Properties();
442
		prop.put("action", action);
443
		prop.put("public", access); //This is the old way of controlling access
444
		prop.put("doctext", xmlDocument);
445
		prop.put("docid", docid);
446
447
		String message = getMetacatString(prop);
448 5311 daigle
		debug("Insert or Update Message: " + message);
449 4080 daigle
		if (message.indexOf("<error>") != -1) {//there was an error
450
451
			return false;
452
		} else if (message.indexOf("<success>") != -1) {//the operation worked
453
			//write the file to the cache and return the file object
454
			return true;
455
456
		} else {//something weird happened.
457
			return false;
458
		}
459
460
	}
461
462
	public boolean handleDeleteFile(String name) {
463
464
		Properties prop = new Properties();
465
		prop.put("action", "delete");
466
		prop.put("docid", name);
467
468
		String message = getMetacatString(prop);
469 5311 daigle
		debug("Delete Message: " + message);
470 4080 daigle
		if (message.indexOf("<error>") != -1) {//there was an error
471
472
			return false;
473
		} else if (message.indexOf("<success>") != -1) {//the operation worked
474
			//write the file to the cache and return the file object
475
			return true;
476
477
		} else {//something weird happened.
478
			return false;
479
		}
480
	}
481
482
	/**
483
	 * sends a data file to the metacat using "multipart/form-data" encoding
484
	 *
485
	 * @param id the id to assign to the file on metacat (e.g., knb.1.1)
486
	 * @param file the file to send
487
	 */
488
	public boolean insertDataFile(String id, File file) {
489
		String response = null;
490
		//Get response for calling sendDataFile function
491
		response = sendDataFile(id, file);
492
493
		if (response.indexOf("success") != -1) {
494
			//insert successfully
495
			return true;
496
		} else {
497
			return false;
498
		}
499
	}
500
501
	/**
502
	 * sends a data file to the metacat using "multipart/form-data" encoding
503
	 *
504
	 * @param id the id to assign to the file on metacat (e.g., knb.1.1)
505
	 * @param file the file to send
506
	 */
507
	public String sendDataFile(String id, File file) {
508
		String response = "";
509
		InputStream returnStream = null;
510
511
		// Now contact metacat and send the request
512
		try {
513
			//FileInputStream data = new FileInputStream(file);
514
			System.setProperty("java.protocol.handler.pkgs", "HTTPClient");
515
			URL url = new URL(metacatURL);
516
			edu.ucsb.nceas.morpho.framework.HttpMessage msg = new edu.ucsb.nceas.morpho.framework.HttpMessage(
517
					url);
518
			Properties args = new Properties();
519
			args.put("action", "upload");
520
			args.put("docid", id);
521
522
			Properties dataStreams = new Properties();
523
			String filename = file.getAbsolutePath();
524
			System.out.println("the absolute path is " + filename);
525
			dataStreams.put("datafile", filename);
526
527
			returnStream = msg.sendPostData(args, dataStreams);
528
529
			InputStreamReader returnStreamReader = new InputStreamReader(returnStream);
530
			StringWriter sw = new StringWriter();
531
			int len;
532
			char[] characters = new char[512];
533
			while ((len = returnStreamReader.read(characters, 0, 512)) != -1) {
534
				sw.write(characters, 0, len);
535
			}
536
			returnStreamReader.close();
537
			response = sw.toString();
538
			sw.close();
539
540
		} catch (Exception e) {
541
			e.printStackTrace(System.err);
542
		}
543
		return response;
544
	}
545
546
	public String getMetacatString(Properties prop) {
547
		String response = null;
548
549
		// Now contact metacat and send the request
550
		try {
551
			InputStreamReader returnStream = new InputStreamReader(
552
					getMetacatInputStream(prop));
553
			StringWriter sw = new StringWriter();
554
			int len;
555
			char[] characters = new char[512];
556
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
557
				sw.write(characters, 0, len);
558
			}
559
			returnStream.close();
560
			response = sw.toString();
561
			sw.close();
562
		} catch (Exception e) {
563
			return null;
564
		}
565
566
		return response;
567
	}
568
569
	/**
570
	 * Send a request to Metacat
571
	 *
572
	 * @param prop the properties to be sent to Metacat
573
	 * @return InputStream as returned by Metacat
574
	 */
575
	public InputStream getMetacatInputStream(Properties prop) {
576
		InputStream returnStream = null;
577
		// Now contact metacat and send the request
578
		try {
579
580
			URL url = new URL(metacatURL);
581
			edu.ucsb.nceas.morpho.framework.HttpMessage msg = new edu.ucsb.nceas.morpho.framework.HttpMessage(
582
					url);
583
			returnStream = msg.sendPostMessage(prop);
584
			return returnStream;
585
		} catch (Exception e) {
586
			e.printStackTrace(System.err);
587
588
		}
589
		return returnStream;
590
591
	}
592
593 1114 tao
}