Project

General

Profile

1 4142 daigle
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2008 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *  Purpose: To test the Access Controls in metacat by JUnit
6
 *
7
 *   '$Author$'
8
 *     '$Date$'
9
 * '$Revision$'
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 2 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program; if not, write to the Free Software
23
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24
 */
25
26
package edu.ucsb.nceas;
27
28
import junit.framework.TestCase;
29
30 5113 daigle
import java.io.BufferedReader;
31 4512 daigle
import java.io.File;
32 5113 daigle
import java.io.FileReader;
33 4382 daigle
import java.io.IOException;
34 5113 daigle
import java.io.InputStreamReader;
35 4512 daigle
import java.io.Reader;
36
import java.io.StringReader;
37 4444 daigle
import java.sql.PreparedStatement;
38
import java.sql.ResultSet;
39
import java.sql.ResultSetMetaData;
40
import java.sql.SQLException;
41
import java.sql.Statement;
42 4512 daigle
import java.util.Calendar;
43
import java.util.Date;
44
import java.util.GregorianCalendar;
45 4444 daigle
import java.util.HashMap;
46
import java.util.Hashtable;
47 4512 daigle
import java.util.SimpleTimeZone;
48
import java.util.TimeZone;
49 4444 daigle
import java.util.Vector;
50 4382 daigle
51 4444 daigle
import org.apache.commons.httpclient.HttpClient;
52
53 5016 daigle
import edu.ucsb.nceas.metacat.database.DBConnection;
54
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
55 4512 daigle
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
56
import edu.ucsb.nceas.metacat.client.Metacat;
57
import edu.ucsb.nceas.metacat.client.MetacatException;
58
import edu.ucsb.nceas.metacat.client.MetacatFactory;
59
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
60 5035 daigle
import edu.ucsb.nceas.metacat.properties.PropertyService;
61 5027 daigle
import edu.ucsb.nceas.metacat.shared.ServiceException;
62 5286 jones
import edu.ucsb.nceas.metacat.util.DocumentUtil;
63 4444 daigle
import edu.ucsb.nceas.metacat.util.RequestUtil;
64 4512 daigle
import edu.ucsb.nceas.utilities.IOUtil;
65 4142 daigle
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
66 4382 daigle
import edu.ucsb.nceas.utilities.SortedProperties;
67 4142 daigle
68
/**
69
 * A base JUnit class for Metacat tests
70
 */
71
public class MCTestCase
72
    extends TestCase {
73
74
    private static boolean printDebug = false;
75 4355 daigle
76
	protected static String EML2_0_0 = "EML2_0_0";
77
	protected static String EML2_0_1 = "EML2_0_1";
78
	protected static String EML2_1_0 = "EML2_1_0";
79 5709 leinfelder
	protected static String EML2_1_1 = "EML2_1_1";
80
81 4142 daigle
82 4355 daigle
	protected boolean SUCCESS = true;
83
	protected boolean FAILURE = false;
84 4444 daigle
85 4512 daigle
	protected static final String ALLOWFIRST = "allowFirst";
86
	protected static final String DENYFIRST = "denyFirst";
87
88 5139 daigle
	protected String testdatadir = "test/clienttestfiles/";
89 4512 daigle
	protected String prefix = "test";
90
	protected String testdocument = "";
91
92 4444 daigle
	protected static HttpClient httpClient = null;
93 4512 daigle
94
	protected static boolean metacatConnectionNeeded = false;
95
	protected Metacat m;
96 4355 daigle
97 4512 daigle
	protected static String metacatUrl;
98
	protected static String username;
99
	protected static String password;
100
	protected static String anotheruser;
101
	protected static String anotherpassword;
102
103 4142 daigle
	static {
104
		try {
105 4382 daigle
			SortedProperties testProperties =
106
				new SortedProperties("build/tests/test.properties");
107
			testProperties.load();
108
			String metacatContextDir = testProperties.getProperty("metacat.contextDir");
109 5035 daigle
			PropertyService.getInstance(metacatContextDir + "/WEB-INF");
110 4719 daigle
//			PropertyService.getInstance();
111 4142 daigle
		    String printDebugString = PropertyService.getProperty("test.printdebug");
112
		    printDebug = Boolean.parseBoolean(printDebugString);
113 4512 daigle
114
		    metacatUrl = PropertyService.getProperty("test.metacatUrl");
115
			username = PropertyService.getProperty("test.mcUser");
116
			password = PropertyService.getProperty("test.mcPassword");
117
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
118
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
119 4382 daigle
		} catch (IOException ioe) {
120
			System.err.println("Could not read property file in static block: "
121
					+ ioe.getMessage());
122 4142 daigle
		} catch (PropertyNotFoundException pnfe) {
123
			System.err.println("Could not get property in static block: "
124
					+ pnfe.getMessage());
125
		} catch (ServiceException se) {
126
			System.err.println("Could not get PropertyService instance in static block: "
127
					+ se.getMessage());
128
		}
129
	}
130 4512 daigle
131
	// header blocks
132
	protected String testEml_200_Header = "<?xml version=\"1.0\"?><eml:eml"
133
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\""
134
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
135
		+ " packageId=\"eml.1.1\" system=\"knb\""
136
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\""
137
		+ " scope=\"system\">";
138
139
	protected String testEml_201_Header = "<?xml version=\"1.0\"?><eml:eml"
140
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\""
141
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
142
		+ " packageId=\"eml.1.1\" system=\"knb\""
143
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\""
144
		+ " scope=\"system\">";
145
146
	protected String testEml_210_Header = "<?xml version=\"1.0\"?><eml:eml"
147
			+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.0\""
148
			+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
149
			+ " packageId=\"eml.1.1\" system=\"knb\""
150
			+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.0 eml.xsd\""
151
			+ " scope=\"system\">";
152 5709 leinfelder
153
	protected String testEml_211_Header = "<?xml version=\"1.0\"?><eml:eml"
154
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.1\""
155
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
156
		+ " packageId=\"eml.1.1\" system=\"knb\""
157
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.1 eml.xsd\""
158
		+ " scope=\"system\">";
159 4148 daigle
160 4512 daigle
	protected String testEmlCreatorBlock = "<creator scope=\"document\">                                       "
161
			+ " <individualName>                                                  "
162
			+ "    <surName>Smith</surName>                                       "
163
			+ " </individualName>                                                 "
164
			+ "</creator>                                                         ";
165
166
	protected String testEmlContactBlock = "<contact scope=\"document\">                                       "
167
			+ " <individualName>                                                  "
168
			+ "    <surName>Jackson</surName>                                     "
169
			+ " </individualName>                                                 "
170
			+ "</contact>                                                         ";
171
172
	protected String testEmlInlineBlock1 = "<inline>                                                           "
173
			+ "  <admin>                                                          "
174
			+ "    <contact>                                                      "
175
			+ "      <name>Operator</name>                                        "
176
			+ "      <institution>PSI</institution>                               "
177
			+ "    </contact>                                                     "
178
			+ "  </admin>                                                         "
179
			+ "</inline>                                                          ";
180
181
	protected String testEmlInlineBlock2 = "<inline>                                                           "
182
			+ "  <instrument>                                                     "
183
			+ "    <instName>LCQ</instName>                                       "
184
			+ "    <source type=\"ESI\"></source>                                 "
185
			+ "    <detector type=\"EM\"></detector>                              "
186
			+ "  </instrument>                                                    "
187
			+ "</inline>                                                          ";
188
189
	/*
190
	 * Retrus an access block base on params passed and the defaul perm order -
191
	 * allow first
192
	 */
193
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
194
			boolean write, boolean changePermission, boolean all) {
195
		return getAccessBlock(principal, grantAccess, read, write, changePermission, all,
196
				ALLOWFIRST);
197
	}
198
199
	/**
200
	 * This function returns an access block based on the params passed
201
	 */
202
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
203
			boolean write, boolean changePermission, boolean all, String permOrder) {
204
		String accessBlock = "<access "
205
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
206
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
207
208
		accessBlock += generateOneAccessRule(principal, grantAccess, read, write,
209
				changePermission, all);
210
		accessBlock += "</access>";
211
212
		return accessBlock;
213
214
	}
215
216
	/*
217
	 * Gets eml access block base on given acccess rules and perm order
218
	 */
219
	protected String getAccessBlock(Vector<String> accessRules, String permOrder) {
220
		String accessBlock = "<access "
221
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
222
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
223
		// adding rules
224
		if (accessRules != null && !accessRules.isEmpty()) {
225
			for (int i = 0; i < accessRules.size(); i++) {
226
				String rule = (String) accessRules.elementAt(i);
227
				accessBlock += rule;
228
229
			}
230
		}
231
		accessBlock += "</access>";
232
		return accessBlock;
233
	}
234
235
	/*
236
	 * Generates a access rule for given parameter. Note this xml portion
237
	 * doesn't include <access></access>
238
	 */
239
	protected String generateOneAccessRule(String principal, boolean grantAccess,
240
			boolean read, boolean write, boolean changePermission, boolean all) {
241
		String accessBlock = "";
242
243
		if (grantAccess) {
244
			accessBlock = "<allow>";
245
		} else {
246
			accessBlock = "<deny>";
247
		}
248
249
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
250
251
		if (all) {
252
			accessBlock += "<permission>all</permission>";
253
		} else {
254
			if (read) {
255
				accessBlock += "<permission>read</permission>";
256
			}
257
			if (write) {
258
				accessBlock += "<permission>write</permission>";
259
			}
260
			if (changePermission) {
261
				accessBlock += "<permission>changePermission</permission>";
262
			}
263
		}
264
265
		if (grantAccess) {
266
			accessBlock += "</allow>";
267
		} else {
268
			accessBlock += "</deny>";
269
		}
270
		return accessBlock;
271
272
	}
273 5759 leinfelder
274
    /**
275
     * This function returns a valid eml document with public read access
276
     */
277
    protected String getTestEmlDoc(String title, String emlVersion) {
278 4512 daigle
279 5759 leinfelder
        String testDocument = "";
280
281
        String header;
282
		if (emlVersion == EML2_0_1) {
283
			header = testEml_201_Header;
284
		} else if (emlVersion == EML2_1_0) {
285
			header = testEml_210_Header;
286
		} else { // if (emlVersion == EML2_1_1) {
287
			header = testEml_211_Header;
288
		}
289
290
        testDocument += header;
291
292
        // if this is an EML 2.1.0 or later document, the document level access is
293
        // before the dataset element.
294
        if (emlVersion == EML2_1_0 || emlVersion == EML2_1_1) {
295
        	testDocument += getAccessBlock("public", true, true, false, false, false);
296
        }
297
        testDocument += "<dataset scope=\"document\"><title>" + title + "</title>"
298
				+ testEmlCreatorBlock;
299
300
        testDocument += testEmlContactBlock;
301
302
        // if this is an EML 2.0.1 or earlier document, the document level access is
303
        // inside the dataset element.
304
        if (emlVersion != EML2_1_0 && emlVersion != EML2_1_1) {
305
        	testDocument += getAccessBlock("public", true, true, false, false, false);
306
        }
307
        testDocument += "</dataset>";
308
        testDocument += "</eml:eml>";
309
310
        return testDocument;
311
    }
312
313 4512 daigle
	/**
314
	 * This function returns a valid eml document with no access rules
315
	 */
316
	protected String getTestEmlDoc(String title, String emlVersion, String inlineData1,
317
			String inlineData2, String onlineUrl1, String onlineUrl2,
318
			String docAccessBlock, String inlineAccessBlock1, String inlineAccessBlock2,
319
			String onlineAccessBlock1, String onlineAccessBlock2) {
320
321
		debug("getTestEmlDoc(): title=" + title + " inlineData1=" + inlineData1
322
				+ " inlineData2=" + inlineData2 + " onlineUrl1=" + onlineUrl1
323
				+ " onlineUrl2=" + onlineUrl2 + " docAccessBlock=" + docAccessBlock
324
				+ " inlineAccessBlock1=" + inlineAccessBlock1 + " inlineAccessBlock2="
325
				+ inlineAccessBlock2 + " onlineAccessBlock1=" + onlineAccessBlock1
326
				+ " onlineAccessBlock2=" + onlineAccessBlock2);
327
		String testDocument = "";
328
		String header;
329
		if (emlVersion == EML2_0_0) {
330
			header = testEml_200_Header;
331
		} else if (emlVersion == EML2_0_1) {
332
			header = testEml_201_Header;
333 5709 leinfelder
		} else if (emlVersion == EML2_1_0) {
334 4512 daigle
			header = testEml_210_Header;
335 5709 leinfelder
		} else { // if (emlVersion == EML2_1_1) {
336
			header = testEml_211_Header;
337 4512 daigle
		}
338
		testDocument += header;
339
340
		// if this is a 2.1.0+ document, the document level access block sits
341
		// at the same level and before the dataset element.
342 5709 leinfelder
		if (docAccessBlock != null && (emlVersion.equals(EML2_1_0) || emlVersion.equals(EML2_1_1))) {
343 4512 daigle
			testDocument += docAccessBlock;
344
		}
345
346
		testDocument += "<dataset scope=\"document\"><title>"
347
				+ title + "</title>" + testEmlCreatorBlock;
348
349
		if (inlineData1 != null) {
350
			testDocument = testDocument
351
					+ "<distribution scope=\"document\" id=\"inlineEntity1\">"
352
					+ inlineData1 + "</distribution>";
353
		}
354
		if (inlineData2 != null) {
355
			testDocument = testDocument
356
					+ "<distribution scope=\"document\" id=\"inlineEntity2\">"
357
					+ inlineData2 + "</distribution>";
358
		}
359
		if (onlineUrl1 != null) {
360
			testDocument = testDocument
361
					+ "<distribution scope=\"document\" id=\"onlineEntity1\">"
362
					+ "<online><url function=\"download\">" + onlineUrl1
363
					+ "</url></online></distribution>";
364
		}
365
		if (onlineUrl2 != null) {
366
			testDocument = testDocument
367
					+ "<distribution scope=\"document\" id=\"onlineEntity2\">"
368
					+ "<online><url function=\"download\">" + onlineUrl2
369
					+ "</url></online></distribution>";
370
		}
371
		testDocument += testEmlContactBlock;
372
373
		// if this is a 2.0.X document, the document level access block sits
374
		// inside the dataset element.
375
		if (docAccessBlock != null &&
376
				(emlVersion.equals(EML2_0_0) || emlVersion.equals(EML2_0_1))) {
377
			testDocument += docAccessBlock;
378
		}
379
380
		testDocument += "</dataset>";
381
382
		if (inlineAccessBlock1 != null) {
383
			testDocument += "<additionalMetadata>";
384
			testDocument += "<describes>inlineEntity1</describes>";
385
			testDocument += inlineAccessBlock1;
386
			testDocument += "</additionalMetadata>";
387
		}
388
389
		if (inlineAccessBlock2 != null) {
390
			testDocument += "<additionalMetadata>";
391
			testDocument += "<describes>inlineEntity2</describes>";
392
			testDocument += inlineAccessBlock2;
393
			testDocument += "</additionalMetadata>";
394
		}
395
396
		if (onlineAccessBlock1 != null) {
397
			testDocument += "<additionalMetadata>";
398
			testDocument += "<describes>onlineEntity1</describes>";
399
			testDocument += onlineAccessBlock1;
400
			testDocument += "</additionalMetadata>";
401
		}
402
403
		if (onlineAccessBlock2 != null) {
404
			testDocument += "<additionalMetadata>";
405
			testDocument += "<describes>onlineEntity2</describes>";
406
			testDocument += onlineAccessBlock2;
407
			testDocument += "</additionalMetadata>";
408
		}
409
410
		testDocument += "</eml:eml>";
411
412
		// System.out.println("Returning following document" + testDocument);
413
		return testDocument;
414
	}
415 5113 daigle
416
	/**
417
	 *
418
	 */
419
	protected String getTestDocFromFile(String filePath) throws IOException{
420
		StringBuffer output = new StringBuffer();
421
422
		FileReader fileReader = new FileReader(new File(filePath));
423
		BufferedReader bufferedReader = new BufferedReader(fileReader);
424
		String readLine = null;
425
426
		while ((readLine = bufferedReader.readLine()) != null) {
427
			output.append(readLine);
428
		}
429
430
		return output.toString();
431
	}
432 4512 daigle
433
434 4148 daigle
    /**
435
     * Constructor to build the test
436
     */
437
    public MCTestCase() {
438
        super();
439
    }
440 4142 daigle
441
    /**
442
     * Constructor to build the test
443
     *
444
     * @param name the name of the test method
445
     */
446
    public MCTestCase(String name) {
447
        super(name);
448
    }
449
450 4512 daigle
	/**
451
	 * Establish a testing framework by initializing appropriate objects
452
	 */
453
	protected void setUp() throws Exception {
454
		try {
455 5139 daigle
			if (metacatConnectionNeeded) {
456
				debug("setUp() - Testing Metacat Url: " + metacatUrl);
457
				m = MetacatFactory.createMetacatConnection(metacatUrl);
458
			}
459 4512 daigle
		} catch (MetacatInaccessibleException mie) {
460
			System.err.println("Metacat is: " + metacatUrl);
461
			fail("Metacat connection failed." + mie.getMessage());
462
		}
463
	}
464
465 4300 daigle
    protected static void debug(String debugMessage) {
466 4142 daigle
    	if (printDebug) {
467
    		System.err.println(debugMessage);
468
    	}
469
    }
470 4444 daigle
471
	protected static Vector<Hashtable<String, Object>> dbSelect(String sqlStatement,
472
			String methodName) throws SQLException {
473
		Vector<Hashtable<String, Object>> resultVector = new Vector<Hashtable<String, Object>>();
474
475
		DBConnectionPool connPool = DBConnectionPool.getInstance();
476
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
477
		int serialNumber = dbconn.getCheckOutSerialNumber();
478
479
		PreparedStatement pstmt = null;
480
481
		debug("Selecting from db: " + sqlStatement);
482
		pstmt = dbconn.prepareStatement(sqlStatement);
483
		pstmt.execute();
484
485
		ResultSet resultSet = pstmt.getResultSet();
486
		ResultSetMetaData rsMetaData = resultSet.getMetaData();
487
		int numColumns = rsMetaData.getColumnCount();
488
		debug("Number of data columns: " + numColumns);
489
		while (resultSet.next()) {
490
			Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
491
			for (int i = 1; i <= numColumns; i++) {
492
				if (resultSet.getObject(i) != null) {
493
					hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i));
494
				}
495
			}
496
			debug("adding data row to result vector");
497
			resultVector.add(hashTable);
498
		}
499
500
		resultSet.close();
501
		pstmt.close();
502
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
503
504
		return resultVector;
505
	}
506
507
	protected static void dbQuery(String sqlStatement, String methodName)
508
			throws SQLException {
509
510
		DBConnectionPool connPool = DBConnectionPool.getInstance();
511
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
512
		int serialNumber = dbconn.getCheckOutSerialNumber();
513
514
		Statement statement = dbconn.createStatement();
515
516
		debug("Executing against db: " + sqlStatement);
517
		statement.executeQuery(sqlStatement);
518
519
		statement.close();
520
521
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
522
	}
523
524
	protected static void dbUpdate(String sqlStatement, String methodName)
525
			throws SQLException {
526
527
		DBConnectionPool connPool = DBConnectionPool.getInstance();
528
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
529
		int serialNumber = dbconn.getCheckOutSerialNumber();
530
531
		Statement statement = dbconn.createStatement();
532
533
		debug("Executing against db: " + sqlStatement);
534
		statement.executeUpdate(sqlStatement);
535
536
		statement.close();
537
538
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
539
	}
540
541
	protected static void httpPost(String url, HashMap<String,String> paramMap)  throws IOException {
542
		debug("Posting to: " + url);
543
		if (httpClient == null) {
544
			httpClient = new HttpClient();
545
		}
546
		String postResponse = RequestUtil.post(httpClient, url, paramMap);
547
		debug("Post response: " + postResponse);
548
		if (postResponse.contains("<error>")) {
549
			fail("Error posting to metacat: " + postResponse);
550
		}
551
	}
552
553
	protected static void resetHttpClient() {
554
		httpClient = null;
555
	}
556 4512 daigle
557
	/**
558
	 * Create a unique docid for testing insert and update. Does not
559
	 * include the 'revision' part of the id.
560
	 *
561
	 * @return a String docid based on the current date and time
562
	 */
563
	protected String generateDocumentId() {
564
		try {
565
			Thread.sleep(1010);
566
		} catch (InterruptedException ie) {
567
			debug("Could not sleep: " + ie.getMessage());
568
		}
569
570 5286 jones
		return DocumentUtil.generateDocumentId(prefix, 0);
571 4512 daigle
	}
572
573
	/**
574
	 * Insert a document into metacat. The expected result is passed as result
575
	 */
576
	protected String insertDocumentId(String docid, String docText, boolean result,
577
			boolean expectKarmaException) {
578 5027 daigle
		debug("insertDocumentId() - docid=" + docid + " expectedResult=" + result
579 4512 daigle
				+ " expectKarmaException=" + expectKarmaException);
580
		String response = null;
581
		try {
582 5113 daigle
			response = m.insert(docid, new StringReader(docText), null);
583 4512 daigle
			if (result) {
584
				assertTrue(response, (response.indexOf("<success>") != -1));
585
				assertTrue(response, response.indexOf(docid) != -1);
586
			} else {
587
				assertTrue(response, (response.indexOf("<success>") == -1));
588
			}
589
			debug("insertDocid():  response=" + response);
590
		} catch (MetacatInaccessibleException mie) {
591
			fail("Metacat Inaccessible:\n" + mie.getMessage());
592
		} catch (InsufficientKarmaException ike) {
593
			if (!expectKarmaException) {
594
				fail("Insufficient karma:\n" + ike.getMessage());
595
			}
596
		} catch (MetacatException me) {
597
			fail("Metacat Error:\n" + me.getMessage());
598
		} catch (Exception e) {
599
			fail("General exception:\n" + e.getMessage());
600
		}
601
		return response;
602
	}
603
604
	/**
605
	 * Insert a document into metacat. The expected result is passed as result
606
	 */
607
608
	protected String uploadDocumentId(String docid, String filePath, boolean result,
609
			boolean expectedKarmaException) {
610 5027 daigle
		debug("uploadDocumentId() - docid=" + docid + " filePath=" + filePath
611 4512 daigle
				+ " expectedResult=" + result + " expectedKarmaException="
612
				+ expectedKarmaException);
613
		String response = null;
614
		try {
615
			response = m.upload(docid, new File(filePath));
616
			if (result) {
617
				assertTrue(response, (response.indexOf("<success>") != -1));
618
				assertTrue(response, response.indexOf(docid) != -1);
619
			} else {
620
				assertTrue(response, (response.indexOf("<success>") == -1));
621
			}
622
			debug("uploadDocid():  response=" + response);
623
		} catch (MetacatInaccessibleException mie) {
624
			fail("Metacat Inaccessible:\n" + mie.getMessage());
625
		} catch (InsufficientKarmaException ike) {
626
			if (!expectedKarmaException) {
627
				fail("Insufficient karma:\n" + ike.getMessage());
628
			}
629
		} catch (MetacatException me) {
630
			if (result) {
631
				fail("Metacat Error:\n" + me.getMessage());
632
			} else {
633
				debug("Metacat Error:\n" + me.getMessage());
634
			}
635
		} catch (Exception e) {
636
			fail("General exception:\n" + e.getMessage());
637
		}
638
		return response;
639
	}
640
641
	/**
642
	 * Update a document in metacat. The expected result is passed as result
643
	 */
644
	protected String updateDocumentId(String docid, String docText, boolean result,
645
			boolean expectedKarmaFailure) {
646 5027 daigle
		debug("updateDocumentId() - docid=" + docid + " expectedResult=" + result
647 4512 daigle
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
648
		String response = null;
649
		try {
650
			response = m.update(docid, new StringReader(testdocument), null);
651 5027 daigle
			debug("updateDocumentId() - response=" + response);
652
653 4512 daigle
			if (result) {
654
				assertTrue(response, (response.indexOf("<success>") != -1));
655
				assertTrue(response, response.indexOf(docid) != -1);
656
			} else {
657
				assertTrue(response, (response.indexOf("<success>") == -1));
658 5027 daigle
			}
659 4512 daigle
		} catch (MetacatInaccessibleException mie) {
660
			fail("Metacat Inaccessible:\n" + mie.getMessage());
661
		} catch (InsufficientKarmaException ike) {
662
			if (!expectedKarmaFailure) {
663
				fail("Insufficient karma:\n" + ike.getMessage());
664
			}
665
		} catch (MetacatException me) {
666
			if (result) {
667
				fail("Metacat Error:\n" + me.getMessage());
668
			} else {
669
				debug("Metacat Error:\n" + me.getMessage());
670
			}
671
		} catch (Exception e) {
672
			fail("General exception:\n" + e.getMessage());
673
		}
674
675
		return response;
676
	}
677
678
	/**
679
	 * Delete a document into metacat. The expected result is passed as result
680
	 */
681
	protected void deleteDocumentId(String docid, boolean result, boolean expectedKarmaFailure) {
682 5027 daigle
		debug("deleteDocumentId() - docid=" + docid + " expectedResult=" + result
683 4512 daigle
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
684
		try {
685
			Thread.sleep(5000);
686
			String response = m.delete(docid);
687 5027 daigle
			debug("deleteDocumentId() -  response=" + response);
688
689 4512 daigle
			if (result) {
690
				assertTrue(response, response.indexOf("<success>") != -1);
691
			} else {
692
				assertTrue(response, response.indexOf("<success>") == -1);
693
			}
694
		} catch (MetacatInaccessibleException mie) {
695
			fail("Metacat Inaccessible:\n" + mie.getMessage());
696
		} catch (InsufficientKarmaException ike) {
697
			if (!expectedKarmaFailure) {
698
				fail("Insufficient karma:\n" + ike.getMessage());
699
			}
700
		} catch (MetacatException me) {
701
			if (result) {
702
				fail("Metacat Error:\n" + me.getMessage());
703
			} else {
704
				debug("Metacat Error:\n" + me.getMessage());
705
			}
706
		} catch (Exception e) {
707
			fail("General exception:\n" + e.getMessage());
708
		}
709
	}
710
711
	/**
712
	 * Read a document from metacat and check if it is equal to a given string.
713
	 * The expected result is passed as result
714
	 */
715
	protected void readDocumentIdWhichEqualsDoc(String docid, String testDoc, boolean result,
716
			boolean expectedKarmaFailure) {
717 5027 daigle
		debug("readDocumentIdWhichEqualsDoc() - docid=" + docid + " expectedResult=" + result
718 4512 daigle
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
719
		try {
720 5113 daigle
			Reader r = new InputStreamReader(m.read(docid));
721 4512 daigle
			String doc = IOUtil.getAsString(r, true);
722 5027 daigle
			debug("readDocumentIdWhichEqualsDoc() -  doc=" + doc);
723
724 4512 daigle
			if (result) {
725
726
				if (!testDoc.equals(doc)) {
727
					System.out.println("doc ***********************");
728
					System.out.println(doc);
729
					System.out.println("end doc ***********************");
730
					System.out.println("testDoc ***********************");
731
					System.out.println(testDoc);
732
					System.out.println("end testDoc ***********************");
733
				}
734
735
				assertTrue(testDoc.equals(doc));
736
			} else {
737
				assertTrue(doc.indexOf("<error>") != -1);
738
			}
739
		} catch (MetacatInaccessibleException mie) {
740
			fail("Metacat Inaccessible:\n" + mie.getMessage());
741
		} catch (InsufficientKarmaException ike) {
742
			if (!expectedKarmaFailure) {
743
				fail("Insufficient karma:\n" + ike.getMessage());
744
			}
745
		} catch (MetacatException me) {
746
			fail("Metacat Error:\n" + me.getMessage());
747
		} catch (Exception e) {
748
			fail("General exception:\n" + e.getMessage());
749
		}
750
751
	}
752
753 4142 daigle
}