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-08-13 08:59:35 -0700 (Wed, 13 Aug 2008) $'
10
 * '$Revision: 4231 $'
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.MCTestCase;
30
import edu.ucsb.nceas.metacat.*;
31
import edu.ucsb.nceas.metacat.service.PropertyService;
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
import org.apache.log4j.Logger;
42

    
43
/**
44
 * A JUnit test for testing Step class processing
45
 */
46
public class MetaCatServletNetTest extends MCTestCase {
47
	private static String metacatURL;
48
	static {
49
		try {		
50
			metacatURL = PropertyService.getProperty("test.metacatUrl");
51
		} 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

    
60
	private String serialNumber;
61
	private static Logger logMetacat = Logger.getLogger(DocumentImpl.class);
62

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

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

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

    
87
	}
88

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

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

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

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

    
119
		suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument", serial));
120

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

    
136
		return suite;
137
	}
138

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

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

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

    
165
	}
166

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

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

    
197
	}
198

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

    
218
	/**
219
	 * Test insert a non well-formed xml document successfully
220
	 * There is no </acl> in this string
221
	 */
222
	public void testInsertNonWellFormedXMLDocument() throws PropertyNotFoundException  {
223
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
224
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
225
		logMetacat.info("insert non well-formed docid: " + name);
226
		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>";
233

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

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

    
246
	}
247

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

    
256
	}
257

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

    
266
	}
267

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

    
288
	}
289

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

    
300
		assertTrue(insertDataFile(name, hello));
301
	}
302

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

    
312
	}
313

    
314
	/**
315
	 * Test logout action
316
	 */
317
	public void testLogOut() {
318

    
319
		assertTrue(handleLogOut());
320

    
321
	}
322

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

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

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

    
345
			connected = false;
346
		}
347

    
348
		return connected;
349
	}
350

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

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

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

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

    
374
		return disConnected;
375
	}
376

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

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

    
395
			return false;
396
		} else {//successfully
397
			return true;
398
		}
399

    
400
	}
401

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

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

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

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

    
431
		} else {//something weird happened.
432
			return false;
433
		}
434

    
435
	}
436

    
437
	public boolean handleDeleteFile(String name) {
438

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

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

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

    
452
		} else {//something weird happened.
453
			return false;
454
		}
455
	}
456

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

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

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

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

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

    
502
			returnStream = msg.sendPostData(args, dataStreams);
503

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

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

    
521
	public String getMetacatString(Properties prop) {
522
		String response = null;
523

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

    
541
		return response;
542
	}
543

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

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

    
563
		}
564
		return returnStream;
565

    
566
	}
567

    
568
}
(1-1/2)