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: leinfelder $'
9
 *     '$Date: 2014-05-29 14:53:36 -0700 (Thu, 29 May 2014) $'
10
 * '$Revision: 8802 $'
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.IdentifierManager;
31
import edu.ucsb.nceas.metacat.client.MetacatClient;
32
import edu.ucsb.nceas.metacat.client.MetacatFactory;
33
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
34
import edu.ucsb.nceas.metacat.properties.PropertyService;
35
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
36

    
37
import junit.framework.Test;
38
import junit.framework.TestSuite;
39

    
40
import java.io.*;
41
import java.net.*;
42
import java.util.*;
43

    
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 MetacatClient metacat = null;
51
	private String serialNumber;
52

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

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

    
73
	/**
74
	 * Constructor to build the test
75
	 * 
76
	 * @param name
77
	 *            the name of the test method
78
	 */
79
	public MetaCatServletTest(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
		try {
89
			metacat = (MetacatClient) MetacatFactory.createMetacatConnection(metacatURL);
90
		} catch (MetacatInaccessibleException e) {
91
			fail("Could not initialize MetacatClient: " + e.getMessage());
92
			e.printStackTrace();
93
		}
94

    
95
	}
96

    
97
	/**
98
	 * Release any objects after tests are complete
99
	 */
100
	public void tearDown() {
101
	}
102

    
103
	/**
104
	 * Create a suite of tests to be run together
105
	 */
106
	public static Test suite() {
107
		double number = 0;
108
		String serial = null;
109

    
110
		TestSuite suite = new TestSuite();
111
		suite.addTest(new MetaCatServletTest("initialize"));
112
		suite.addTest(new MetaCatServletTest("testLterReferralLogin"));
113
		suite.addTest(new MetaCatServletTest("testLterReferralLoginFail"));
114
		suite.addTest(new MetaCatServletTest("testOtherReferralLogin"));
115
		suite.addTest(new MetaCatServletTest("testOtherReferralLoginFail"));
116
		suite.addTest(new MetaCatServletTest("testNCEASLoginFail"));
117
		// Should put a login successfully at the end of login test
118
		// So insert or update can have cookie.
119
		suite.addTest(new MetaCatServletTest("testNCEASLogin"));
120

    
121
		// create random number for docid, so it can void repeat
122
		number = Math.random() * 100000;
123
		serial = Integer.toString(((new Double(number)).intValue()));
124
		debug("serial: " + serial);
125
		suite.addTest(new MetaCatServletTest("testInsertXMLDocument", serial));
126
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentXMLFormat", serial));
127
		suite.addTest(new MetaCatServletTest("testUpdateXMLDocument", serial));
128

    
129
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentHTMLFormat", serial));
130
		suite.addTest(new MetaCatServletTest("testReadXMLDocumentZipFormat", serial));
131

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

    
145
		suite.addTest(new MetaCatServletTest("testLogOut"));
146
		
147
		suite.addTest(new MetaCatServletTest("testReindexFail"));
148
		
149
		
150
		return suite;
151
	}
152

    
153
	/**
154
	 * Run an initial test that always passes to check that the test harness is
155
	 * working.
156
	 */
157
	public void initialize() {
158
		assertTrue(1 == 1);
159
	}
160

    
161
	/**
162
	 * Test the login to neceas succesfully
163
	 */
164
    public void testNCEASLogin() {
165
        debug("\nRunning: testNCEASLogin test");
166
        try {
167
            String user = PropertyService.getProperty("test.mcUser");
168
            String passwd = PropertyService.getProperty("test.mcPassword");
169
            assertTrue(logIn(user, passwd));
170
        } catch (PropertyNotFoundException pnfe) {
171
            fail("Could not find property: " + pnfe.getMessage());
172
        }
173
    }
174

    
175
	/**
176
	 * Test the login to neceas failed
177
	 */
178
	public void testNCEASLoginFail() {
179
		debug("\nRunning: testNCEASLoginFail test");
180
        try {
181
            String user = PropertyService.getProperty("test.mcUser");
182
            String passwd = "BogusPasswordShouldFail";
183
            assertTrue(!logIn(user, passwd));
184
        } catch (PropertyNotFoundException pnfe) {
185
            fail("Could not find property: " + pnfe.getMessage());
186
        }
187
	}
188

    
189
	/**
190
	 * Test the login to lter succesfully
191
	 */
192
	public void testLterReferralLogin() {
193
		debug("\nRunning: testLterReferralLogin test");
194
		String user = null;
195
		String passwd = null;
196
		try {
197
			user = PropertyService.getProperty("test.lterUser");
198
			passwd = PropertyService.getProperty("test.lterPassword");
199
		} catch (PropertyNotFoundException pnfe) {
200
			fail("Could not find property: " + pnfe.getMessage());
201
		}
202

    
203
		debug("Logging into lter: " + user + " : " + passwd);
204
		assertTrue(logIn(user, passwd));
205

    
206
	}
207

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

    
224
	/**
225
	 * Test the login to Other succesfully
226
	 */
227
	public void testOtherReferralLogin() {
228
		debug("\nRunning: testOtherReferralLogin test");
229
		String user = null;
230
		String passwd = null;
231
		try {
232
			user = PropertyService.getProperty("test.referralUser");
233
			passwd = PropertyService.getProperty("test.referralPassword");
234
		} catch (PropertyNotFoundException pnfe) {
235
			fail("Could not find property: " + pnfe.getMessage());
236
		}
237
		debug("logging in Other user: " + user + ":" + passwd);
238
		assertTrue(logIn(user, passwd));
239
		// assertTrue( withProtocol.getProtocol().equals("http"));
240
	}
241

    
242
	/**
243
	 * Test the login to Other failed
244
	 */
245
	public void testOtherReferralLoginFail() {
246
		debug("\nRunning: testOtherReferralLoginFail test");
247
		String user = null;
248
    String passwd = "wrong";
249
    try {
250
      user = PropertyService.getProperty("test.referralUser");
251
    } catch (PropertyNotFoundException pnfe) {
252
      fail("Could not find property: " + pnfe.getMessage());
253
    }
254
		assertTrue(!logIn(user, passwd));
255
		// assertTrue( withProtocol.getProtocol().equals("http"));
256
	}
257
	
258

    
259

    
260
	/**
261
	 * Test insert a xml document successfully
262
	 */
263
    public void testInsertXMLDocument() {
264
        debug("\nRunning: testInsertXMLDocument test");
265
        String name = null;
266
        try {
267
            String user = PropertyService.getProperty("test.mcUser");
268
            String passwd = PropertyService.getProperty("test.mcPassword");
269

    
270
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
271
                    + "1";
272
            debug("insert docid: " + name);
273
            String content = "<?xml version=\"1.0\"?>" + "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
274
                    + "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb.edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
275
                    + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>" + "<principal>" + user
276
                    + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
277
                    + "<permission>read</permission>" + "</allow>" + "</acl>";
278
            debug("xml document: " + content);
279
            assertTrue(handleXMLDocument(content, name, "insert"));
280
        } catch (PropertyNotFoundException pnfe) {
281
            fail("Could not find property: " + pnfe.getMessage());
282
        }
283
    }
284

    
285
	/**
286
	 * Test insert a invalidate xml document successfully In the String, there
287
	 * is no <!Doctype ... Public/System/>
288
	 */
289
    public void testInsertInvalidateXMLDocument() {
290
        debug("\nRunning: testInsertInvalidateXMLDocument test");
291
        String name = null;
292
        try {
293
            String user = PropertyService.getProperty("test.mcUser");
294
            String passwd = PropertyService.getProperty("test.mcPassword");
295

    
296
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
297
                    + "1";
298
            debug("insert docid: " + name);
299
            String content = "<?xml version=\"1.0\"?>" + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>"
300
                    + "<principal>" + user + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
301
                    + "<permission>read</permission>" + "</allow>" + "</acl>";
302
            debug("xml document: " + content);
303
            assertTrue(handleXMLDocument(content, name, "insert"));
304
        } catch (PropertyNotFoundException pnfe) {
305
            fail("Could not find property: " + pnfe.getMessage());
306
        }
307
    }
308

    
309
	/**
310
	 * Test insert a non well-formed xml document successfully There is no
311
	 * </acl> in this string
312
	 */
313
    public void testInsertNonWellFormedXMLDocument() {
314
        debug("\nRunning: testInsertNonWellFormedXMLDocument test");
315
        String name = null;
316
        try {
317
            String user = PropertyService.getProperty("test.mcUser");
318
            String passwd = PropertyService.getProperty("test.mcPassword");
319

    
320
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
321
                    + "1";
322
            debug("insert non well-formed docid: " + name);
323
            String content = "<?xml version=\"1.0\"?>" + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>"
324
                    + "<principal>" + user + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
325
                    + "<permission>read</permission>" + "</allow>";
326

    
327
            debug("xml document: " + content);
328
            assertTrue(!handleXMLDocument(content, name, "insert"));
329
        } catch (PropertyNotFoundException pnfe) {
330
            fail("Could not find property: " + pnfe.getMessage());
331
        }
332
    }
333

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

    
349
	}
350

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

    
366
	}
367

    
368
	/**
369
	 * Test read a xml document in zip format successfully
370
	 */
371
	public void testReadXMLDocumentZipFormat() {
372
		debug("\nRunning: testReadXMLDocumentZipFormat test");
373
		String name = null;
374
		try {
375
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
376
					+ serialNumber
377
					+ PropertyService.getProperty("document.accNumSeparator") + "1";
378
		} catch (PropertyNotFoundException pnfe) {
379
			fail("Could not find property: " + pnfe.getMessage());
380
		}
381
		assertTrue(handleReadAction(name, "zip"));
382

    
383
	}
384

    
385
	/**
386
	 * Test insert a xml document successfully
387
	 */
388
    public void testUpdateXMLDocument() {
389
        debug("\nRunning: testUpdateXMLDocument test");
390
        String name = null;
391
        try {
392
            String user = PropertyService.getProperty("test.mcUser");
393
            String passwd = PropertyService.getProperty("test.mcPassword");
394

    
395
            name = "john" + PropertyService.getProperty("document.accNumSeparator") + serialNumber + PropertyService.getProperty("document.accNumSeparator")
396
                    + "2";
397
            debug("update docid: " + name);
398
            String content = "<?xml version=\"1.0\"?>" + "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
399
                    + "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb." + "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
400
                    + "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name + "</identifier>" + "<allow>" + "<principal>" + user
401
                    + "</principal>" + "<permission>all</permission>" + "</allow>" + "<allow>" + "<principal>public</principal>"
402
                    + "<permission>read</permission>" + "</allow>" + "</acl>";
403
            debug("xml document: " + content);
404
            assertTrue(handleXMLDocument(content, name, "update"));
405
        } catch (PropertyNotFoundException pnfe) {
406
            fail("Could not find property: " + pnfe.getMessage());
407
        }
408
    }
409

    
410
	/**
411
	 * Test delete a xml document successfully
412
	 */
413
	public void testDeleteXMLDocument() {
414
		debug("\nRunning: testDeleteXMLDocument test");
415
		String name = null;
416
		try {
417
			name = "john" + PropertyService.getProperty("document.accNumSeparator")
418
					+ serialNumber
419
					+ PropertyService.getProperty("document.accNumSeparator") + "2";
420
		} catch (PropertyNotFoundException pnfe) {
421
			fail("Could not find property: " + pnfe.getMessage());
422
		}
423
		debug("delete docid: " + name);
424
		assertTrue(handleDeleteFile(name));
425

    
426
	}
427

    
428
    
429
	/**
430
	 * Test logout action
431
	 */
432
	public void testLogOut() {
433
		debug("\nRunning: testLogOut test");
434
		assertTrue(handleLogOut());
435

    
436
	}
437
	
438
	public void testReindexFail() {
439

    
440
		// find a pid to reindex
441
		String identifier = null;
442
		List<String> ids = IdentifierManager.getInstance().getAllSystemMetadataGUIDs();
443
		if (ids != null && !ids.isEmpty()) {
444
			identifier = ids.get(0);
445
		}
446
		Properties prop = new Properties();
447
		prop.put("action", "reindex");
448
		prop.put("pid", identifier);
449

    
450
		String message = getMetacatString(prop);
451
		debug("Reindex Message: " + message);
452
		if (message.indexOf("<error>") != -1) {// there was an error
453
			assertTrue(true);
454
		} else if (message.indexOf("<success>") != -1) {
455
			fail("Unauthenticated user should not be able to invoke this action: " + message);
456
		} else {// something weird happened.
457
			fail("There was an unexpected error reindexing pid: " + message);
458
		}
459
	}
460

    
461
	/**
462
	 * Method to hanld login action
463
	 * 
464
	 * @param usrerName,
465
	 *            the DN name of the test method
466
	 * @param passWord,
467
	 *            the passwd of the user
468
	 */
469

    
470
	public boolean logIn(String userName, String passWord) {
471
		Properties prop = new Properties();
472
		prop.put("action", "login");
473
		prop.put("qformat", "xml");
474
		prop.put("username", userName);
475
		prop.put("password", passWord);
476

    
477
		// Now contact metacat
478
		String response = getMetacatString(prop);
479
		debug("Login Message: " + response);
480
		boolean connected = false;
481
		if (response != null && response.indexOf("<login>") != -1) {
482
			connected = true;
483
		} else {
484

    
485
			connected = false;
486
		}
487

    
488
		return connected;
489
	}
490

    
491
	/**
492
	 * Method to hanld logout action
493
	 * 
494
	 * @param usrerName,
495
	 *            the DN name of the test method
496
	 * @param passWord,
497
	 *            the passwd of the user
498
	 */
499

    
500
	public boolean handleLogOut() {
501
		boolean disConnected = false;
502
		Properties prop = new Properties();
503
		prop.put("action", "logout");
504
		prop.put("qformat", "xml");
505

    
506
		String response = getMetacatString(prop);
507
		debug("Logout Message: " + response);
508

    
509
		if (response.indexOf("<logout>") != -1) {
510
			disConnected = true;
511
		} else {
512
			disConnected = false;
513
		}
514

    
515
		return disConnected;
516
	}
517

    
518
	/**
519
	 * Method to hanld read both xml and data file
520
	 * 
521
	 * @param docid,
522
	 *            the docid of the document want to read
523
	 * @param qformat,
524
	 *            the format of document user want to get
525
	 */
526
	public boolean handleReadAction(String docid, String qformat) {
527
		Properties prop = new Properties();
528
		String message = "";
529
		prop.put("action", "read");
530
		prop.put("qformat", qformat);
531
		prop.put("docid", docid);
532

    
533
		message = getMetacatString(prop);
534
		message = message.trim();
535
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {// there
536
																						// was
537
																						// an
538
																						// error
539

    
540
			return false;
541
		} else {// successfully
542
			return true;
543
		}
544

    
545
	}
546

    
547
	/**
548
	 * Method to hanld inset or update xml document
549
	 * 
550
	 * @param xmlDocument,
551
	 *            the content of xml qformat
552
	 * @param docid,
553
	 *            the docid of the document
554
	 * @param action,
555
	 *            insert or update
556
	 */
557
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
558

    
559
	{ // -attempt to write file to metacat
560
		String access = "no";
561
		StringBuffer fileText = new StringBuffer();
562
		StringBuffer messageBuf = new StringBuffer();
563
		String accessFileId = null;
564
		Properties prop = new Properties();
565
		prop.put("action", action);
566
		prop.put("public", access); // This is the old way of controlling access
567
		prop.put("doctext", xmlDocument);
568
		prop.put("docid", docid);
569

    
570
		String message = getMetacatString(prop);
571
		debug("Insert or Update Message: " + message);
572
		if (message.indexOf("<error>") != -1) {// there was an error
573

    
574
			return false;
575
		} else if (message.indexOf("<success>") != -1) {// the operation worked
576
			// write the file to the cache and return the file object
577
			return true;
578

    
579
		} else {// something weird happened.
580
			return false;
581
		}
582

    
583
	}
584

    
585
	public boolean handleDeleteFile(String name) {
586

    
587
		Properties prop = new Properties();
588
		prop.put("action", "delete");
589
		prop.put("docid", name);
590

    
591
		String message = getMetacatString(prop);
592
		debug("Delete Message: " + message);
593
		if (message.indexOf("<error>") != -1) {// there was an error
594

    
595
			return false;
596
		} else if (message.indexOf("<success>") != -1) {// the operation worked
597
			// write the file to the cache and return the file object
598
			return true;
599

    
600
		} else {// something weird happened.
601
			return false;
602
		}
603
	}
604

    
605
	public String getMetacatString(Properties prop) {
606
		String response = null;
607

    
608
		// Now contact metacat and send the request
609
		try {
610
			InputStreamReader returnStream = new InputStreamReader(
611
					getMetacatInputStream(prop));
612
			StringWriter sw = new StringWriter();
613
			int len;
614
			char[] characters = new char[512];
615
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
616
				sw.write(characters, 0, len);
617
			}
618
			returnStream.close();
619
			response = sw.toString();
620
			sw.close();
621
		} catch (Exception e) {
622
			return null;
623
		}
624

    
625
		return response;
626
	}
627

    
628
	/**
629
	 * Send a request to Metacat
630
	 * 
631
	 * @param prop
632
	 *            the properties to be sent to Metacat
633
	 * @return InputStream as returned by Metacat
634
	 */
635
	public InputStream getMetacatInputStream(Properties prop) {
636
		InputStream returnStream = null;
637
		// Now contact metacat and send the request
638
		try {
639

    
640
			returnStream = metacat.sendParameters(prop);
641
			return returnStream;
642
		} catch (Exception e) {
643
			e.printStackTrace(System.err);
644

    
645
		}
646
		return returnStream;
647

    
648
	}
649

    
650
}
(11-11/26)