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