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-15 10:11:14 -0700 (Tue, 15 Jul 2008) $'
10
 * '$Revision: 4125 $'
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.utilities.PropertyNotFoundException;
32
import edu.ucsb.nceas.morpho.framework.*;
33
import junit.framework.Test;
34
import junit.framework.TestCase;
35
import junit.framework.TestResult;
36
import junit.framework.TestSuite;
37

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

    
42
import org.apache.log4j.Logger;
43

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

    
62
	private String serialNumber;
63
	private static Logger logMetacat = Logger.getLogger(DocumentImpl.class);
64

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

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

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

    
89
	}
90

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

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

    
104
		TestSuite suite = new TestSuite();
105
		suite.addTest(new MetaCatServletNetTest("initialize"));
106
		suite.addTest(new MetaCatServletNetTest("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 MetaCatServletNetTest("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
		logMetacat.info("serial: " + serial);
115
		suite.addTest(new MetaCatServletNetTest("testInsertXMLDocument", serial));
116
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentXMLFormat", serial));
117
		suite.addTest(new MetaCatServletNetTest("testUpdateXMLDocument", serial));
118
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentHTMLFormat", serial));
119
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentZipFormat", serial));
120

    
121
		suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument", serial));
122

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

    
138
		return suite;
139
	}
140

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

    
149
	/**
150
	 * Test the login to neceas succesfully
151
	 */
152
	public void testNCEASLogin() {
153
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
154
		String passwd = "123456";
155
		assertTrue(logIn(user, passwd));
156
		//assertTrue( withProtocol.getProtocol().equals("http"));
157
	}
158

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

    
167
	}
168

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

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

    
199
	}
200

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

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

    
236
		logMetacat.info("xml document: " + content);
237
		assertTrue(!handleXMLDocument(content, name, "insert"));
238
	}
239

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

    
248
	}
249

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

    
258
	}
259

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

    
268
	}
269

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

    
290
	}
291

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

    
302
		assertTrue(insertDataFile(name, hello));
303
	}
304

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

    
314
	}
315

    
316
	/**
317
	 * Test logout action
318
	 */
319
	public void testLogOut() {
320

    
321
		assertTrue(handleLogOut());
322

    
323
	}
324

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

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

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

    
347
			connected = false;
348
		}
349

    
350
		return connected;
351
	}
352

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

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

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

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

    
376
		return disConnected;
377
	}
378

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

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

    
397
			return false;
398
		} else {//successfully
399
			return true;
400
		}
401

    
402
	}
403

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

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

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

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

    
433
		} else {//something weird happened.
434
			return false;
435
		}
436

    
437
	}
438

    
439
	public boolean handleDeleteFile(String name) {
440

    
441
		Properties prop = new Properties();
442
		prop.put("action", "delete");
443
		prop.put("docid", name);
444

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

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

    
454
		} else {//something weird happened.
455
			return false;
456
		}
457
	}
458

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

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

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

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

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

    
504
			returnStream = msg.sendPostData(args, dataStreams);
505

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

    
517
		} catch (Exception e) {
518
			e.printStackTrace(System.err);
519
		}
520
		return response;
521
	}
522

    
523
	public String getMetacatString(Properties prop) {
524
		String response = null;
525

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

    
543
		return response;
544
	}
545

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

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

    
565
		}
566
		return returnStream;
567

    
568
	}
569

    
570
}
(1-1/2)