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: rnahf $'
9
 *     '$Date: 2011-04-25 14:28:11 -0700 (Mon, 25 Apr 2011) $'
10
 * '$Revision: 6047 $'
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.metacattest;
28

    
29
import edu.ucsb.nceas.MCTestCase;
30
import edu.ucsb.nceas.metacat.dataone.CrudServiceTest;
31
import edu.ucsb.nceas.metacat.properties.PropertyService;
32
import edu.ucsb.nceas.utilities.HttpMessage;
33
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
34

    
35
import junit.framework.Test;
36
import junit.framework.TestSuite;
37

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

    
42
import org.dataone.service.types.AuthToken;
43
import org.dataone.service.types.Identifier;
44

    
45
/**
46
 * A JUnit test for testing Step class processing
47
 */
48
public class MetaCatServletTest extends MCTestCase {
49
	private static String metacatURL;
50
	private String serialNumber;
51

    
52
	/* Initialize properties */
53
	static {
54
		try {
55
			metacatURL = PropertyService.getProperty("test.metacatUrl");
56
		} catch (PropertyNotFoundException pnfe) {
57
			System.err.println("Could not get property in static block: "
58
					+ pnfe.getMessage());
59
		}
60
	}
61

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

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

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

    
88
	}
89

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

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

    
103
		TestSuite suite = new TestSuite();
104
		suite.addTest(new MetaCatServletTest("initialize"));
105
		suite.addTest(new MetaCatServletTest("testLterReferralLogin"));
106
		suite.addTest(new MetaCatServletTest("testLterReferralLoginFail"));
107
		// the pisco referral isn't working in test environment, so commenting out the tests
108
		//		suite.addTest(new MetaCatServletTest("testPiscoReferralLogin"));
109
		//      suite.addTest(new MetaCatServletTest("testPiscoReferralLoginFail"));
110
		suite.addTest(new MetaCatServletTest("testNCEASLoginFail"));
111
		// Should put a login successfully at the end of login test
112
		// So insert or update can have cookie.
113
		suite.addTest(new MetaCatServletTest("testNCEASLogin"));
114

    
115
		// create random number for docid, so it can void repeat
116
		number = Math.random() * 100000;
117
		serial = Integer.toString(((new Double(number)).intValue()));
118
		debug("serial: " + serial);
119
		suite.addTest(new MetaCatServletTest("testInsertXMLDocument", serial));
120
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentXMLFormat", serial));
121
		suite.addTest(new MetaCatServletTest("testUpdateXMLDocument", serial));
122
    
123
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentHTMLFormat", serial));
124
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentZipFormat", serial));
125
    
126
		suite.addTest(new MetaCatServletTest("testDeleteXMLDocument", serial));
127
		
128
		// test delete using GUID
129
		number = Math.random() * 100000;
130
		serial = Integer.toString(((new Double(number)).intValue()));
131
		suite.addTest(new MetaCatServletTest("testDeleteDocumentByGUID", serial));
132

    
133
		// insert invalid xml document
134
		number = Math.random() * 100000;
135
		serial = Integer.toString(((new Double(number)).intValue()));
136
		suite.addTest(new MetaCatServletTest("testInsertInvalidateXMLDocument", serial));
137
		// insert non well formed document
138
		number = Math.random() * 100000;
139
		serial = Integer.toString(((new Double(number)).intValue()));
140
		suite
141
				.addTest(new MetaCatServletTest("testInsertNonWellFormedXMLDocument",
142
						serial));
143
    
144
		suite.addTest(new MetaCatServletTest("testLogOut"));
145

    
146
		return suite;
147
	}
148

    
149
	/**
150
	 * Run an initial test that always passes to check that the test harness is
151
	 * working.
152
	 */
153
	public void initialize() {
154
		assertTrue(1 == 1);
155
	}
156

    
157
	/**
158
	 * Test the login to neceas succesfully
159
	 */
160
	public void testNCEASLogin() {
161
		debug("\nRunning: testNCEASLogin test");
162
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
163
		String passwd = "123456";
164
		assertTrue(logIn(user, passwd));
165
		// assertTrue( withProtocol.getProtocol().equals("http"));
166
	}
167

    
168
	/**
169
	 * Test the login to neceas failed
170
	 */
171
	public void testNCEASLoginFail() {
172
		debug("\nRunning: testNCEASLoginFail test");
173
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
174
		String passwd = "12345678";
175
		assertTrue(!logIn(user, passwd));
176

    
177
	}
178

    
179
	/**
180
	 * Test the login to lter succesfully
181
	 */
182
	public void testLterReferralLogin() {
183
		debug("\nRunning: testLterReferralLogin test");
184
		String user = null;
185
		String passwd = null;
186
		try {
187
			user = PropertyService.getProperty("test.lterUser");
188
			passwd = PropertyService.getProperty("test.lterPassword");
189
		} catch (PropertyNotFoundException pnfe) {
190
			fail("Could not find property: " + pnfe.getMessage());
191
		}
192

    
193
		debug("Logging into lter: " + user + " : " + passwd);
194
		assertTrue(logIn(user, passwd));
195

    
196
	}
197

    
198
	/**
199
	 * Test the login to lter failed
200
	 */
201
	public void testLterReferralLoginFail() {
202
		debug("\nRunning: testLterReferralLoginFail test");
203
		String user = "uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
204
		String passwd = "qVyGpveb";
205
		assertTrue(!logIn(user, passwd));
206
		// assertTrue( withProtocol.getProtocol().equals("http"));
207
	}
208

    
209
	/**
210
	 * Test the login to pisco succesfully
211
	 */
212
	public void testPiscoReferralLogin() {
213
		debug("\nRunning: testPiscoReferralLogin test");
214
		String user = null;
215
		String passwd = null;
216
		try {
217
			user = PropertyService.getProperty("test.piscoUser");
218
			passwd = PropertyService.getProperty("test.piscoPassword");
219
		} catch (PropertyNotFoundException pnfe) {
220
			fail("Could not find property: " + pnfe.getMessage());
221
		}
222
		debug("logging in pisco user: " + user + ":" + passwd);
223
		assertTrue(logIn(user, passwd));
224
		// assertTrue( withProtocol.getProtocol().equals("http"));
225
	}
226

    
227
	/**
228
	 * Test the login to pisco failed
229
	 */
230
	public void testPiscoReferralLoginFail() {
231
		debug("\nRunning: testPiscoReferralLoginFail test");
232
		String user = "uid=tao,o=PISCO,dc=ecoinformatics,dc=org";
233
		String passwd = "hello";
234
		assertTrue(!logIn(user, passwd));
235
		// assertTrue( withProtocol.getProtocol().equals("http"));
236
	}
237

    
238
	/**
239
	 * Test insert a xml document successfully
240
	 */
241
	public void testInsertXMLDocument() {
242
		debug("\nRunning: testInsertXMLDocument test");
243
		String name = null;
244
		try {
245
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
246
					+ serialNumber
247
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
248
		} catch (PropertyNotFoundException pnfe) {
249
			fail("Could not find property: " + pnfe.getMessage());
250
		}
251
		debug("insert docid: " + name);
252
		String content = "<?xml version=\"1.0\"?>"
253
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
254
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
255
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
256
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
257
				+ "</identifier>" + "<allow>"
258
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
259
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
260
				+ "<principal>public</principal>" + "<permission>read</permission>"
261
				+ "</allow>" + "</acl>";
262
		debug("xml document: " + content);
263
		assertTrue(handleXMLDocument(content, name, "insert"));
264

    
265
	}
266

    
267
	/**
268
	 * Test insert a invalidate xml document successfully In the String, there
269
	 * is no <!Doctype ... Public/System/>
270
	 */
271
	public void testInsertInvalidateXMLDocument() {
272
		debug("\nRunning: testInsertInvalidateXMLDocument test");
273
		String name = null;
274
		try {
275
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
276
					+ serialNumber
277
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
278
		} catch (PropertyNotFoundException pnfe) {
279
			fail("Could not find property: " + pnfe.getMessage());
280
		}
281
		debug("insert docid: " + name);
282
		String content = "<?xml version=\"1.0\"?>"
283
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
284
				+ "</identifier>" + "<allow>"
285
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
286
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
287
				+ "<principal>public</principal>" + "<permission>read</permission>"
288
				+ "</allow>" + "</acl>";
289
		debug("xml document: " + content);
290
		assertTrue(handleXMLDocument(content, name, "insert"));
291
	}
292

    
293
	/**
294
	 * Test insert a non well-formed xml document successfully There is no
295
	 * </acl> in this string
296
	 */
297
	public void testInsertNonWellFormedXMLDocument() {
298
		debug("\nRunning: testInsertNonWellFormedXMLDocument test");
299
		String name = null;
300
		try {
301
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
302
					+ serialNumber
303
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
304
		} catch (PropertyNotFoundException pnfe) {
305
			fail("Could not find property: " + pnfe.getMessage());
306
		}
307
		debug("insert non well-formed docid: " + name);
308
		String content = "<?xml version=\"1.0\"?>"
309
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
310
				+ "</identifier>" + "<allow>"
311
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
312
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
313
				+ "<principal>public</principal>" + "<permission>read</permission>"
314
				+ "</allow>";
315

    
316
		debug("xml document: " + content);
317
		assertTrue(!handleXMLDocument(content, name, "insert"));
318
	}
319

    
320
	/**
321
	 * Test read a xml document in xml format successfully
322
	 */
323
	public void testReadXMLDocumentXMLFormat() {
324
		debug("\nRunning: testReadXMLDocumentXMLFormat test");
325
		String name = null;
326
		try {
327
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
328
					+ serialNumber
329
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
330
		} catch (PropertyNotFoundException pnfe) {
331
			fail("Could not find property: " + pnfe.getMessage());
332
		}
333
		assertTrue(handleReadAction(name, "xml"));
334

    
335
	}
336

    
337
	/**
338
	 * Test read a xml document in html format successfully
339
	 */
340
	public void testReadXMLDocumentHTMLFormat() {
341
		debug("\nRunning: testReadXMLDocumentHTMLFormat test");
342
		String name = null;
343
		try {
344
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
345
					+ serialNumber
346
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
347
		} catch (PropertyNotFoundException pnfe) {
348
			fail("Could not find property: " + pnfe.getMessage());
349
		}
350
		assertTrue(handleReadAction(name, "html"));
351

    
352
	}
353

    
354
	/**
355
	 * Test read a xml document in zip format successfully
356
	 */
357
	public void testReadXMLDocumentZipFormat() {
358
		debug("\nRunning: testReadXMLDocumentZipFormat test");
359
		String name = null;
360
		try {
361
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
362
					+ serialNumber
363
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
364
		} catch (PropertyNotFoundException pnfe) {
365
			fail("Could not find property: " + pnfe.getMessage());
366
		}
367
		assertTrue(handleReadAction(name, "zip"));
368

    
369
	}
370

    
371
	/**
372
	 * Test insert a xml document successfully
373
	 */
374
	public void testUpdateXMLDocument() {
375
		debug("\nRunning: testUpdateXMLDocument test");
376
		String name = null;
377
		try {
378
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
379
					+ serialNumber
380
					+ PropertyService.getProperty("document.accNumSeparator") + "2";
381
		} catch (PropertyNotFoundException pnfe) {
382
			fail("Could not find property: " + pnfe.getMessage());
383
		}
384
		debug("update docid: " + name);
385
		String content = "<?xml version=\"1.0\"?>"
386
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
387
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
388
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
389
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
390
				+ "</identifier>" + "<allow>"
391
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
392
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
393
				+ "<principal>public</principal>" + "<permission>read</permission>"
394
				+ "</allow>" + "</acl>";
395
		debug("xml document: " + content);
396
		assertTrue(handleXMLDocument(content, name, "update"));
397

    
398
	}
399

    
400
	/**
401
	 * Test delete a xml document successfully
402
	 */
403
	public void testDeleteXMLDocument() {
404
		debug("\nRunning: testDeleteXMLDocument test");
405
		String name = null;
406
		try {
407
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
408
					+ serialNumber
409
					+ PropertyService.getProperty("document.accNumSeparator") + "2";
410
		} catch (PropertyNotFoundException pnfe) {
411
			fail("Could not find property: " + pnfe.getMessage());
412
		}
413
		debug("delete docid: " + name);
414
		assertTrue(handleDeleteFile(name));
415

    
416
	}
417

    
418
  /**
419
   * Test to delete a document by GUID (not docid).  This exercises 
420
   * MetacatServlet.handleDeleteAction()'s handling of GUIDs.
421
   */
422
  public void testDeleteDocumentByGUID() {
423
    debug("\nRunning: testDeleteDocumentByGUID test");
424
    
425
    CrudServiceTest crudServiceTest = new CrudServiceTest("testDeleteDocumentByGUID");
426
    String guid = "";
427
    String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
428
		String passwd = "123456";
429
		AuthToken token = null;
430
		String result = "";
431
    // create a document via the CRUD service to get a GUID
432
    try {
433
      token = crudServiceTest.getToken(user, passwd);
434
      String testDocument = crudServiceTest.getTestDoc();
435
      Identifier identifier = crudServiceTest.createDoc(token, testDocument);
436
      guid = identifier.getValue();
437
      
438
    } catch (Exception e) {
439
      fail("Could not create test document to delete: " + e.getMessage());
440
      
441
    }
442
    
443
    // delete the document via the Metacat servlet with the GUID
444
    try {
445
      Properties props = new Properties();
446
      props.put("action", "delete");
447
      props.put("docid", guid);
448
      props.put("sessionid", token.getToken());
449
      debug("Trying to delete by GUID: " + guid);
450
      result = getMetacatString(props);
451
        
452
    } catch ( Exception e ) {
453
      fail("Couldn't delete GUID: " + guid);
454
        
455
    }
456
    
457
    assertTrue(result.indexOf("<success>") > 0);
458
    
459
  }
460
	/**
461
	 * Test logout action
462
	 */
463
	public void testLogOut() {
464
		debug("\nRunning: testLogOut test");
465
		assertTrue(handleLogOut());
466

    
467
	}
468

    
469
	/**
470
	 * Method to hanld login action
471
	 * 
472
	 * @param usrerName,
473
	 *            the DN name of the test method
474
	 * @param passWord,
475
	 *            the passwd of the user
476
	 */
477

    
478
	public boolean logIn(String userName, String passWord) {
479
		Properties prop = new Properties();
480
		prop.put("action", "login");
481
		prop.put("qformat", "xml");
482
		prop.put("username", userName);
483
		prop.put("password", passWord);
484

    
485
		// Now contact metacat
486
		String response = getMetacatString(prop);
487
		debug("Login Message: " + response);
488
		boolean connected = false;
489
		if (response.indexOf("<login>") != -1) {
490
			connected = true;
491
		} else {
492

    
493
			connected = false;
494
		}
495

    
496
		return connected;
497
	}
498

    
499
	/**
500
	 * Method to hanld logout action
501
	 * 
502
	 * @param usrerName,
503
	 *            the DN name of the test method
504
	 * @param passWord,
505
	 *            the passwd of the user
506
	 */
507

    
508
	public boolean handleLogOut() {
509
		boolean disConnected = false;
510
		Properties prop = new Properties();
511
		prop.put("action", "logout");
512
		prop.put("qformat", "xml");
513

    
514
		String response = getMetacatString(prop);
515
		debug("Logout Message: " + response);
516
		HttpMessage.setCookie(null);
517

    
518
		if (response.indexOf("<logout>") != -1) {
519
			disConnected = true;
520
		} else {
521
			disConnected = false;
522
		}
523

    
524
		return disConnected;
525
	}
526

    
527
	/**
528
	 * Method to hanld read both xml and data file
529
	 * 
530
	 * @param docid,
531
	 *            the docid of the document want to read
532
	 * @param qformat,
533
	 *            the format of document user want to get
534
	 */
535
	public boolean handleReadAction(String docid, String qformat) {
536
		Properties prop = new Properties();
537
		String message = "";
538
		prop.put("action", "read");
539
		prop.put("qformat", qformat);
540
		prop.put("docid", docid);
541

    
542
		message = getMetacatString(prop);
543
		message = message.trim();
544
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {// there
545
																						// was
546
																						// an
547
																						// error
548

    
549
			return false;
550
		} else {// successfully
551
			return true;
552
		}
553

    
554
	}
555

    
556
	/**
557
	 * Method to hanld inset or update xml document
558
	 * 
559
	 * @param xmlDocument,
560
	 *            the content of xml qformat
561
	 * @param docid,
562
	 *            the docid of the document
563
	 * @param action,
564
	 *            insert or update
565
	 */
566
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
567

    
568
	{ // -attempt to write file to metacat
569
		String access = "no";
570
		StringBuffer fileText = new StringBuffer();
571
		StringBuffer messageBuf = new StringBuffer();
572
		String accessFileId = null;
573
		Properties prop = new Properties();
574
		prop.put("action", action);
575
		prop.put("public", access); // This is the old way of controlling access
576
		prop.put("doctext", xmlDocument);
577
		prop.put("docid", docid);
578

    
579
		String message = getMetacatString(prop);
580
		debug("Insert or Update Message: " + message);
581
		if (message.indexOf("<error>") != -1) {// there was an error
582

    
583
			return false;
584
		} else if (message.indexOf("<success>") != -1) {// the operation worked
585
			// write the file to the cache and return the file object
586
			return true;
587

    
588
		} else {// something weird happened.
589
			return false;
590
		}
591

    
592
	}
593

    
594
	public boolean handleDeleteFile(String name) {
595

    
596
		Properties prop = new Properties();
597
		prop.put("action", "delete");
598
		prop.put("docid", name);
599

    
600
		String message = getMetacatString(prop);
601
		debug("Delete Message: " + message);
602
		if (message.indexOf("<error>") != -1) {// there was an error
603

    
604
			return false;
605
		} else if (message.indexOf("<success>") != -1) {// the operation worked
606
			// write the file to the cache and return the file object
607
			return true;
608

    
609
		} else {// something weird happened.
610
			return false;
611
		}
612
	}
613

    
614
	public String getMetacatString(Properties prop) {
615
		String response = null;
616

    
617
		// Now contact metacat and send the request
618
		try {
619
			InputStreamReader returnStream = new InputStreamReader(
620
					getMetacatInputStream(prop));
621
			StringWriter sw = new StringWriter();
622
			int len;
623
			char[] characters = new char[512];
624
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
625
				sw.write(characters, 0, len);
626
			}
627
			returnStream.close();
628
			response = sw.toString();
629
			sw.close();
630
		} catch (Exception e) {
631
			return null;
632
		}
633

    
634
		return response;
635
	}
636

    
637
	/**
638
	 * Send a request to Metacat
639
	 * 
640
	 * @param prop
641
	 *            the properties to be sent to Metacat
642
	 * @return InputStream as returned by Metacat
643
	 */
644
	public InputStream getMetacatInputStream(Properties prop) {
645
		InputStream returnStream = null;
646
		// Now contact metacat and send the request
647
		try {
648

    
649
			URL url = new URL(metacatURL);
650
			HttpMessage msg = new HttpMessage(url);
651
			returnStream = msg.sendPostMessage(prop);
652
			return returnStream;
653
		} catch (Exception e) {
654
			e.printStackTrace(System.err);
655

    
656
		}
657
		return returnStream;
658

    
659
	}
660

    
661
}
(10-10/24)