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: cjones $'
9
 *     '$Date: 2011-03-03 08:15:37 -0800 (Thu, 03 Mar 2011) $'
10
 * '$Revision: 6006 $'
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
		suite.addTest(new MetaCatServletTest("testPiscoReferralLogin"));
108
		suite.addTest(new MetaCatServletTest("testPiscoReferralLoginFail"));
109
		suite.addTest(new MetaCatServletTest("testNCEASLoginFail"));
110
		// Should put a login successfully at the end of login test
111
		// So insert or update can have cookie.
112
		suite.addTest(new MetaCatServletTest("testNCEASLogin"));
113

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

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

    
145
		return suite;
146
	}
147

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

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

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

    
176
	}
177

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

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

    
195
	}
196

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

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

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

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

    
264
	}
265

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

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

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

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

    
334
	}
335

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

    
351
	}
352

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

    
368
	}
369

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

    
397
	}
398

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

    
415
	}
416

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

    
466
	}
467

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

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

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

    
492
			connected = false;
493
		}
494

    
495
		return connected;
496
	}
497

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

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

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

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

    
523
		return disConnected;
524
	}
525

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

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

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

    
553
	}
554

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

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

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

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

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

    
591
	}
592

    
593
	public boolean handleDeleteFile(String name) {
594

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

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

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

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

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

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

    
633
		return response;
634
	}
635

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

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

    
655
		}
656
		return returnStream;
657

    
658
	}
659

    
660
}
(10-10/24)