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: jones $'
9
 *     '$Date: 2011-04-14 03:41:31 -0700 (Thu, 14 Apr 2011) $'
10
 * '$Revision: 6038 $'
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.properties.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

    
62
	/**
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

    
71
	/**
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

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

    
86
	}
87

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

    
94
	/**
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

    
101
		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

    
108
		//create random number for docid, so it can void repeat
109
		number = Math.random() * 100000;
110
		serial = Integer.toString(((new Double(number)).intValue()));
111
		debug("serial: " + serial);
112
		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

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

    
120
		//insert invalid xml document
121
		number = Math.random() * 100000;
122
		serial = Integer.toString(((new Double(number)).intValue()));
123
		suite.addTest(new MetaCatServletNetTest("testInsertInvalidateXMLDocument",
124
						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

    
135
		return suite;
136
	}
137

    
138
	/**
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

    
146
	/**
147
	 * Test the login to nceas succesfully
148
	 */
149
	public void testNCEASLogin() {
150
	    System.out.println("Testing nceas login");
151
	    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
	}
162

    
163
	/**
164
	 * Test the login to nceas failed
165
	 */
166
    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

    
174
        } catch (PropertyNotFoundException e) {
175
            fail(e.getMessage());
176
        }
177
    }
178

    
179
	/**
180
	 * Test the login to lter failed
181
	 */
182
	public void testLterReferralLoginFail() {
183
		debug("\nRunning: testLterReferralLoginFail test");
184
        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
	}
193

    
194
	/**
195
	 * Test insert a xml document successfully
196
	 */
197
	public void testInsertXMLDocument() throws PropertyNotFoundException {
198
		debug("\nRunning: testInsertXMLDocument test");
199
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
200
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
201
		debug("insert docid: " + name);
202
		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
		debug("xml document: " + content);
213
		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
		debug("\nRunning: testInsertInvalidateXMLDocument test");
223
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
224
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
225
		debug("insert 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>" + "</acl>";
233
		debug("xml document: " + content);
234
		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
		debug("\nRunning: testInsertNonWellFormedXMLDocument test");
243
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
244
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
245
		debug("insert non well-formed docid: " + name);
246
		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
		debug("xml document: " + content);
255
		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
		debug("\nRunning: testReadXMLDocumentXMLFormat test");
263
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
264
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
265
		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
		debug("\nRunning: testReadXMLDocumentHTMLFormat test");
274
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
275
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
276
		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
		debug("\nRunning: testReadXMLDocumentZipFormat test");
285
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
286
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
287
		assertTrue(handleReadAction(name, "zip"));
288

    
289
	}
290

    
291
	/**
292
	 * Test insert a xml document successfully
293
	 */
294
	public void testUpdateXMLDocument() throws PropertyNotFoundException {
295
		debug("\nRunning: testUpdateXMLDocument test");
296
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
297
				+ PropertyService.getProperty("document.accNumSeparator") + "2";
298
		debug("update docid: " + name);
299
		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
		debug("xml document: " + content);
310
		assertTrue(handleXMLDocument(content, name, "update"));
311

    
312
	}
313

    
314
	/**
315
	 * Test insert a data file successfully
316
	 */
317
	public void testInertDataFile() throws PropertyNotFoundException {
318
		debug("\nRunning: testInertDataFile test");
319
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
320
				+ PropertyService.getProperty("document.accNumSeparator") + "1";
321
		debug("insert data file docid: " + name);
322
		debug("insert data file ");
323
		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
		debug("\nRunning: testDeleteXMLDocument test");
333
		String name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber
334
				+ PropertyService.getProperty("document.accNumSeparator") + "2";
335
		debug("delete docid: " + name);
336
		assertTrue(handleDeleteFile(name));
337
	}
338

    
339
	/**
340
	 * Test logout action
341
	 */
342
	public void testLogOut() {
343
		debug("\nRunning: testLogOut test");
344
		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
		debug("Login Message: " + response);
365
		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
		debug("Logout Message: " + response);
391
		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
		//MetacatUtil.debugMessage("Read Message: "+message, 30);
418
		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
		debug("Insert or Update Message: " + message);
449
		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
		debug("Delete Message: " + message);
470
		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
}
(1-1/2)