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: daigle $'
9
 *     '$Date: 2008-07-06 21:25:34 -0700 (Sun, 06 Jul 2008) $'
10
 * '$Revision: 4080 $'
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.metacatnettest;
28

    
29
import edu.ucsb.nceas.metacat.*;
30
import edu.ucsb.nceas.metacat.service.PropertyService;
31
import edu.ucsb.nceas.metacat.util.SystemUtil;
32
import edu.ucsb.nceas.utilities.Options;
33
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
34
import edu.ucsb.nceas.morpho.framework.*;
35
import junit.framework.Test;
36
import junit.framework.TestCase;
37
import junit.framework.TestResult;
38
import junit.framework.TestSuite;
39

    
40
import java.io.*;
41
import java.net.*;
42
import java.util.*;
43

    
44
import org.apache.log4j.Logger;
45

    
46
/**
47
 * A JUnit test for testing Step class processing
48
 */
49
public class MetaCatServletNetTest extends TestCase {
50
	private static String metacatURL;
51
	static {
52
		try {
53
			metacatURL = SystemUtil.getServletURL();
54
			Options.initialize(new File("build/tests/metacat.properties"));
55
		} catch (PropertyNotFoundException pnfe) {
56
			System.err.println("could not find metacat URL in MetacatServletNetTest: "
57
					+ pnfe.getMessage());
58
		} catch (Exception e) {
59
			System.err.println("Exception in initialize option in MetacatServletNetTest: "
60
					+ e.getMessage());
61
		}
62
	}
63

    
64
	private String serialNumber;
65
	private static Logger logMetacat = Logger.getLogger(DocumentImpl.class);
66

    
67
	/**
68
	 * Constructor to build the test
69
	 *
70
	 * @param name the name of the test method
71
	 */
72
	public MetaCatServletNetTest(String name) {
73
		super(name);
74
	}
75

    
76
	/**
77
	 * Constructor to build the test
78
	 *
79
	 * @param name the name of the test method
80
	 */
81
	public MetaCatServletNetTest(String name, String serial) {
82
		super(name);
83
		serialNumber = serial;
84
	}
85

    
86
	/**
87
	 * Establish a testing framework by initializing appropriate objects
88
	 */
89
	public void setUp() {
90

    
91
	}
92

    
93
	/**
94
	 * Release any objects after tests are complete
95
	 */
96
	public void tearDown() {
97
	}
98

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

    
106
		TestSuite suite = new TestSuite();
107
		suite.addTest(new MetaCatServletNetTest("initialize"));
108
		suite.addTest(new MetaCatServletNetTest("testNCEASLoginFail"));
109
		//Should put a login successfully at the end of login test
110
		//So insert or update can have cookie.
111
		suite.addTest(new MetaCatServletNetTest("testNCEASLogin"));
112

    
113
		//create random number for docid, so it can void repeat
114
		number = Math.random() * 100000;
115
		serial = Integer.toString(((new Double(number)).intValue()));
116
		logMetacat.info("serial: " + serial);
117
		suite.addTest(new MetaCatServletNetTest("testInsertXMLDocument", serial));
118
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentXMLFormat", serial));
119
		suite.addTest(new MetaCatServletNetTest("testUpdateXMLDocument", serial));
120
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentHTMLFormat", serial));
121
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentZipFormat", serial));
122

    
123
		suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument", serial));
124

    
125
		//insert invalid xml document
126
		number = Math.random() * 100000;
127
		serial = Integer.toString(((new Double(number)).intValue()));
128
		suite
129
				.addTest(new MetaCatServletNetTest("testInsertInvalidateXMLDocument",
130
						serial));
131
		//insert non well formed document
132
		number = Math.random() * 100000;
133
		serial = Integer.toString(((new Double(number)).intValue()));
134
		suite.addTest(new MetaCatServletNetTest("testInsertNonWellFormedXMLDocument",
135
				serial));
136
		//insert data file  
137
		number = Math.random() * 100000;
138
		serial = Integer.toString(((new Double(number)).intValue()));
139
		suite.addTest(new MetaCatServletNetTest("testLogOut"));
140

    
141
		return suite;
142
	}
143

    
144
	/**
145
	 * Run an initial test that always passes to check that the test
146
	 * harness is 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
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
157
		String passwd = "123456";
158
		assertTrue(logIn(user, passwd));
159
		//assertTrue( withProtocol.getProtocol().equals("http"));
160
	}
161

    
162
	/**
163
	 * Test the login to neceas failed
164
	 */
165
	public void testNCEASLoginFail() {
166
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
167
		String passwd = "12345678";
168
		assertTrue(!logIn(user, passwd));
169

    
170
	}
171

    
172
	/**
173
	 * Test the login to lter failed
174
	 */
175
	public void testLterReferralLoginFail() {
176
		String user = "uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
177
		String passwd = "qVyGpveb";
178
		assertTrue(!logIn(user, passwd));
179
		//assertTrue( withProtocol.getProtocol().equals("http"));
180
	}
181

    
182
	/**
183
	 * Test insert a xml document successfully
184
	 */
185
	public void testInsertXMLDocument() throws PropertyNotFoundException {
186
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
187
				+ PropertyService.getProperty("accNumSeparator") + "1";
188
		logMetacat.info("insert docid: " + name);
189
		String content = "<?xml version=\"1.0\"?>"
190
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
191
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
192
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
193
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
194
				+ "</identifier>" + "<allow>"
195
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
196
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
197
				+ "<principal>public</principal>" + "<permission>read</permission>"
198
				+ "</allow>" + "</acl>";
199
		logMetacat.info("xml document: " + content);
200
		assertTrue(handleXMLDocument(content, name, "insert"));
201

    
202
	}
203

    
204
	/**
205
	 * Test insert a invalidate xml document successfully
206
	 * In the String, there is no <!Doctype ... Public/System/>
207
	 */
208
	public void testInsertInvalidateXMLDocument() throws PropertyNotFoundException  {
209
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
210
				+ PropertyService.getProperty("accNumSeparator") + "1";
211
		logMetacat.info("insert docid: " + name);
212
		String content = "<?xml version=\"1.0\"?>"
213
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
214
				+ "</identifier>" + "<allow>"
215
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
216
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
217
				+ "<principal>public</principal>" + "<permission>read</permission>"
218
				+ "</allow>" + "</acl>";
219
		logMetacat.info("xml document: " + content);
220
		assertTrue(handleXMLDocument(content, name, "insert"));
221
	}
222

    
223
	/**
224
	 * Test insert a non well-formed xml document successfully
225
	 * There is no </acl> in this string
226
	 */
227
	public void testInsertNonWellFormedXMLDocument() throws PropertyNotFoundException  {
228
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
229
				+ PropertyService.getProperty("accNumSeparator") + "1";
230
		logMetacat.info("insert non well-formed docid: " + name);
231
		String content = "<?xml version=\"1.0\"?>"
232
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
233
				+ "</identifier>" + "<allow>"
234
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
235
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
236
				+ "<principal>public</principal>" + "<permission>read</permission>"
237
				+ "</allow>";
238

    
239
		logMetacat.info("xml document: " + content);
240
		assertTrue(!handleXMLDocument(content, name, "insert"));
241
	}
242

    
243
	/**
244
	 * Test read a xml document  in xml format successfully
245
	 */
246
	public void testReadXMLDocumentXMLFormat() throws PropertyNotFoundException  {
247
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
248
				+ PropertyService.getProperty("accNumSeparator") + "1";
249
		assertTrue(handleReadAction(name, "xml"));
250

    
251
	}
252

    
253
	/**
254
	 * Test read a xml document  in html format successfully
255
	 */
256
	public void testReadXMLDocumentHTMLFormat() throws PropertyNotFoundException {
257
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
258
				+ PropertyService.getProperty("accNumSeparator") + "1";
259
		assertTrue(handleReadAction(name, "html"));
260

    
261
	}
262

    
263
	/**
264
	 * Test read a xml document  in zip format successfully
265
	 */
266
	public void testReadXMLDocumentZipFormat() throws PropertyNotFoundException {
267
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
268
				+ PropertyService.getProperty("accNumSeparator") + "1";
269
		assertTrue(handleReadAction(name, "zip"));
270

    
271
	}
272

    
273
	/**
274
	 * Test insert a xml document successfully
275
	 */
276
	public void testUpdateXMLDocument() throws PropertyNotFoundException {
277
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
278
				+ PropertyService.getProperty("accNumSeparator") + "2";
279
		logMetacat.info("update docid: " + name);
280
		String content = "<?xml version=\"1.0\"?>"
281
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
282
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
283
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
284
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
285
				+ "</identifier>" + "<allow>"
286
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
287
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
288
				+ "<principal>public</principal>" + "<permission>read</permission>"
289
				+ "</allow>" + "</acl>";
290
		logMetacat.info("xml document: " + content);
291
		assertTrue(handleXMLDocument(content, name, "update"));
292

    
293
	}
294

    
295
	/**
296
	 * Test insert a data file successfully
297
	 */
298
	public void testInertDataFile() throws PropertyNotFoundException {
299
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
300
				+ PropertyService.getProperty("accNumSeparator") + "1";
301
		logMetacat.info("insert data file docid: " + name);
302
		logMetacat.info("insert data file ");
303
		File hello = new File("test/jones.204.22.xml");
304

    
305
		assertTrue(insertDataFile(name, hello));
306
	}
307

    
308
	/**
309
	 * Test delete a xml document successfully
310
	 */
311
	public void testDeleteXMLDocument() throws PropertyNotFoundException {
312
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
313
				+ PropertyService.getProperty("accNumSeparator") + "2";
314
		logMetacat.info("delete docid: " + name);
315
		assertTrue(handleDeleteFile(name));
316

    
317
	}
318

    
319
	/**
320
	 * Test logout action
321
	 */
322
	public void testLogOut() {
323

    
324
		assertTrue(handleLogOut());
325

    
326
	}
327

    
328
	/**
329
	 * Method to hanld login action
330
	 *
331
	 * @param usrerName, the DN name of the test method
332
	 * @param passWord, the passwd of the user
333
	 */
334

    
335
	public boolean logIn(String userName, String passWord) {
336
		Properties prop = new Properties();
337
		prop.put("action", "login");
338
		prop.put("qformat", "xml");
339
		prop.put("username", userName);
340
		prop.put("password", passWord);
341

    
342
		// Now contact metacat
343
		String response = getMetacatString(prop);
344
		logMetacat.info("Login Message: " + response);
345
		boolean connected = false;
346
		if (response.indexOf("<login>") != -1) {
347
			connected = true;
348
		} else {
349

    
350
			connected = false;
351
		}
352

    
353
		return connected;
354
	}
355

    
356
	/**
357
	 * Method to hanld logout action
358
	 *
359
	 * @param usrerName, the DN name of the test method
360
	 * @param passWord, the passwd of the user
361
	 */
362

    
363
	public boolean handleLogOut() {
364
		boolean disConnected = false;
365
		Properties prop = new Properties();
366
		prop.put("action", "logout");
367
		prop.put("qformat", "xml");
368

    
369
		String response = getMetacatString(prop);
370
		logMetacat.info("Logout Message: " + response);
371
		edu.ucsb.nceas.morpho.framework.HttpMessage.setCookie(null);
372

    
373
		if (response.indexOf("<logout>") != -1) {
374
			disConnected = true;
375
		} else {
376
			disConnected = false;
377
		}
378

    
379
		return disConnected;
380
	}
381

    
382
	/**
383
	 * Method to hanld read both xml and data file
384
	 *
385
	 * @param docid, the docid of the document want to read
386
	 * @param qformat, the format of document user want to get
387
	 */
388
	public boolean handleReadAction(String docid, String qformat) {
389
		Properties prop = new Properties();
390
		String message = "";
391
		prop.put("action", "read");
392
		prop.put("qformat", qformat);
393
		prop.put("docid", docid);
394

    
395
		message = getMetacatString(prop);
396
		message = message.trim();
397
		//MetaCatUtil.debugMessage("Read Message: "+message, 30);
398
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {//there was an error
399

    
400
			return false;
401
		} else {//successfully
402
			return true;
403
		}
404

    
405
	}
406

    
407
	/**
408
	 * Method to hanld inset or update xml document
409
	 *
410
	 * @param xmlDocument, the content of xml qformat
411
	 * @param docid, the docid of the document
412
	 * @param action, insert or update
413
	 */
414
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
415

    
416
	{ //-attempt to write file to metacat
417
		String access = "no";
418
		StringBuffer fileText = new StringBuffer();
419
		StringBuffer messageBuf = new StringBuffer();
420
		String accessFileId = null;
421
		Properties prop = new Properties();
422
		prop.put("action", action);
423
		prop.put("public", access); //This is the old way of controlling access
424
		prop.put("doctext", xmlDocument);
425
		prop.put("docid", docid);
426

    
427
		String message = getMetacatString(prop);
428
		logMetacat.info("Insert or Update Message: " + message);
429
		if (message.indexOf("<error>") != -1) {//there was an error
430

    
431
			return false;
432
		} else if (message.indexOf("<success>") != -1) {//the operation worked
433
			//write the file to the cache and return the file object
434
			return true;
435

    
436
		} else {//something weird happened.
437
			return false;
438
		}
439

    
440
	}
441

    
442
	public boolean handleDeleteFile(String name) {
443

    
444
		Properties prop = new Properties();
445
		prop.put("action", "delete");
446
		prop.put("docid", name);
447

    
448
		String message = getMetacatString(prop);
449
		logMetacat.info("Delete Message: " + message);
450
		if (message.indexOf("<error>") != -1) {//there was an error
451

    
452
			return false;
453
		} else if (message.indexOf("<success>") != -1) {//the operation worked
454
			//write the file to the cache and return the file object
455
			return true;
456

    
457
		} else {//something weird happened.
458
			return false;
459
		}
460
	}
461

    
462
	/**
463
	 * sends a data file to the metacat using "multipart/form-data" encoding
464
	 *
465
	 * @param id the id to assign to the file on metacat (e.g., knb.1.1)
466
	 * @param file the file to send
467
	 */
468
	public boolean insertDataFile(String id, File file) {
469
		String response = null;
470
		//Get response for calling sendDataFile function
471
		response = sendDataFile(id, file);
472

    
473
		if (response.indexOf("success") != -1) {
474
			//insert successfully
475
			return true;
476
		} else {
477
			return false;
478
		}
479
	}
480

    
481
	/**
482
	 * sends a data file to the metacat using "multipart/form-data" encoding
483
	 *
484
	 * @param id the id to assign to the file on metacat (e.g., knb.1.1)
485
	 * @param file the file to send
486
	 */
487
	public String sendDataFile(String id, File file) {
488
		String response = "";
489
		InputStream returnStream = null;
490

    
491
		// Now contact metacat and send the request
492
		try {
493
			//FileInputStream data = new FileInputStream(file);
494
			System.setProperty("java.protocol.handler.pkgs", "HTTPClient");
495
			URL url = new URL(metacatURL);
496
			edu.ucsb.nceas.morpho.framework.HttpMessage msg = new edu.ucsb.nceas.morpho.framework.HttpMessage(
497
					url);
498
			Properties args = new Properties();
499
			args.put("action", "upload");
500
			args.put("docid", id);
501

    
502
			Properties dataStreams = new Properties();
503
			String filename = file.getAbsolutePath();
504
			System.out.println("the absolute path is " + filename);
505
			dataStreams.put("datafile", filename);
506

    
507
			returnStream = msg.sendPostData(args, dataStreams);
508

    
509
			InputStreamReader returnStreamReader = new InputStreamReader(returnStream);
510
			StringWriter sw = new StringWriter();
511
			int len;
512
			char[] characters = new char[512];
513
			while ((len = returnStreamReader.read(characters, 0, 512)) != -1) {
514
				sw.write(characters, 0, len);
515
			}
516
			returnStreamReader.close();
517
			response = sw.toString();
518
			sw.close();
519

    
520
		} catch (Exception e) {
521
			e.printStackTrace(System.err);
522
		}
523
		return response;
524
	}
525

    
526
	public String getMetacatString(Properties prop) {
527
		String response = null;
528

    
529
		// Now contact metacat and send the request
530
		try {
531
			InputStreamReader returnStream = new InputStreamReader(
532
					getMetacatInputStream(prop));
533
			StringWriter sw = new StringWriter();
534
			int len;
535
			char[] characters = new char[512];
536
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
537
				sw.write(characters, 0, len);
538
			}
539
			returnStream.close();
540
			response = sw.toString();
541
			sw.close();
542
		} catch (Exception e) {
543
			return null;
544
		}
545

    
546
		return response;
547
	}
548

    
549
	/**
550
	 * Send a request to Metacat
551
	 *
552
	 * @param prop the properties to be sent to Metacat
553
	 * @return InputStream as returned by Metacat
554
	 */
555
	public InputStream getMetacatInputStream(Properties prop) {
556
		InputStream returnStream = null;
557
		// Now contact metacat and send the request
558
		try {
559

    
560
			URL url = new URL(metacatURL);
561
			edu.ucsb.nceas.morpho.framework.HttpMessage msg = new edu.ucsb.nceas.morpho.framework.HttpMessage(
562
					url);
563
			returnStream = msg.sendPostMessage(prop);
564
			return returnStream;
565
		} catch (Exception e) {
566
			e.printStackTrace(System.err);
567

    
568
		}
569
		return returnStream;
570

    
571
	}
572

    
573
}
(1-1/2)