Project

General

Profile

1
/**
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: leinfelder $'
8
 *     '$Date: 2011-02-04 06:17:53 -0800 (Fri, 04 Feb 2011) $'
9
 * '$Revision: 5914 $'
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
import java.io.BufferedReader;
31
import java.io.File;
32
import java.io.FileReader;
33
import java.io.IOException;
34
import java.io.InputStreamReader;
35
import java.io.Reader;
36
import java.io.StringReader;
37
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
import java.util.Calendar;
43
import java.util.Date;
44
import java.util.GregorianCalendar;
45
import java.util.HashMap;
46
import java.util.Hashtable;
47
import java.util.SimpleTimeZone;
48
import java.util.TimeZone;
49
import java.util.Vector;
50

    
51
import org.apache.http.client.HttpClient;
52
import org.apache.http.impl.client.DefaultHttpClient;
53

    
54
import edu.ucsb.nceas.metacat.database.DBConnection;
55
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
56
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
57
import edu.ucsb.nceas.metacat.client.Metacat;
58
import edu.ucsb.nceas.metacat.client.MetacatException;
59
import edu.ucsb.nceas.metacat.client.MetacatFactory;
60
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
61
import edu.ucsb.nceas.metacat.properties.PropertyService;
62
import edu.ucsb.nceas.metacat.shared.ServiceException;
63
import edu.ucsb.nceas.metacat.util.DocumentUtil;
64
import edu.ucsb.nceas.metacat.util.RequestUtil;
65
import edu.ucsb.nceas.utilities.IOUtil;
66
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
67
import edu.ucsb.nceas.utilities.SortedProperties;
68

    
69
/**
70
 * A base JUnit class for Metacat tests
71
 */
72
public class MCTestCase
73
    extends TestCase {
74
	
75
    private static boolean printDebug = false;
76
    
77
	protected static String EML2_0_0 = "EML2_0_0";
78
	protected static String EML2_0_1 = "EML2_0_1";
79
	protected static String EML2_1_0 = "EML2_1_0";
80
	protected static String EML2_1_1 = "EML2_1_1";
81

    
82
	
83
	protected boolean SUCCESS = true;
84
	protected boolean FAILURE = false;
85
	
86
	protected static final String ALLOWFIRST = "allowFirst";
87
	protected static final String DENYFIRST = "denyFirst";
88
	
89
	protected String testdatadir = "test/clienttestfiles/";
90
	protected String prefix = "test";
91
	protected String testdocument = "";
92
	
93
	protected static HttpClient httpClient = null;
94
	
95
	protected static boolean metacatConnectionNeeded = false;
96
	protected Metacat m;
97

    
98
	protected static String metacatUrl;
99
	protected static String username;
100
	protected static String password;
101
	protected static String anotheruser;
102
	protected static String anotherpassword;
103
	
104
	static {
105
		try {
106
			SortedProperties testProperties = 
107
				new SortedProperties("build/tests/test.properties");
108
			testProperties.load();
109
			String metacatContextDir = testProperties.getProperty("metacat.contextDir");
110
			PropertyService.getInstance(metacatContextDir + "/WEB-INF");
111
//			PropertyService.getInstance();
112
		    String printDebugString = PropertyService.getProperty("test.printdebug");
113
		    printDebug = Boolean.parseBoolean(printDebugString);
114

    
115
		    metacatUrl = PropertyService.getProperty("test.metacatUrl");
116
			username = PropertyService.getProperty("test.mcUser");
117
			password = PropertyService.getProperty("test.mcPassword");
118
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
119
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
120
		} catch (IOException ioe) {
121
			System.err.println("Could not read property file in static block: " 
122
					+ ioe.getMessage());
123
		} catch (PropertyNotFoundException pnfe) {
124
			System.err.println("Could not get property in static block: " 
125
					+ pnfe.getMessage());
126
		} catch (ServiceException se) {
127
			System.err.println("Could not get PropertyService instance in static block: " 
128
					+ se.getMessage());
129
		}
130
	}
131
	
132
	// header blocks
133
	protected String testEml_200_Header = "<?xml version=\"1.0\"?><eml:eml"
134
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\""
135
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
136
		+ " packageId=\"eml.1.1\" system=\"knb\""
137
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\""
138
		+ " scope=\"system\">";
139
	
140
	protected String testEml_201_Header = "<?xml version=\"1.0\"?><eml:eml"
141
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\""
142
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
143
		+ " packageId=\"eml.1.1\" system=\"knb\""
144
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\""
145
		+ " scope=\"system\">";
146
	
147
	protected String testEml_210_Header = "<?xml version=\"1.0\"?><eml:eml"
148
			+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.0\""
149
			+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
150
			+ " packageId=\"eml.1.1\" system=\"knb\""
151
			+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.0 eml.xsd\""
152
			+ " scope=\"system\">";
153
	
154
	protected String testEml_211_Header = "<?xml version=\"1.0\"?><eml:eml"
155
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.1\""
156
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
157
		+ " packageId=\"eml.1.1\" system=\"knb\""
158
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.1 eml.xsd\""
159
		+ " scope=\"system\">";
160

    
161
	protected String testEmlCreatorBlock = "<creator scope=\"document\">                                       "
162
			+ " <individualName>                                                  "
163
			+ "    <surName>Smith</surName>                                       "
164
			+ " </individualName>                                                 "
165
			+ "</creator>                                                         ";
166

    
167
	protected String testEmlContactBlock = "<contact scope=\"document\">                                       "
168
			+ " <individualName>                                                  "
169
			+ "    <surName>Jackson</surName>                                     "
170
			+ " </individualName>                                                 "
171
			+ "</contact>                                                         ";
172

    
173
	protected String testEmlInlineBlock1 = "<inline>                                                           "
174
			+ "  <admin>                                                          "
175
			+ "    <contact>                                                      "
176
			+ "      <name>Operator</name>                                        "
177
			+ "      <institution>PSI</institution>                               "
178
			+ "    </contact>                                                     "
179
			+ "  </admin>                                                         "
180
			+ "</inline>                                                          ";
181

    
182
	protected String testEmlInlineBlock2 = "<inline>                                                           "
183
			+ "  <instrument>                                                     "
184
			+ "    <instName>LCQ</instName>                                       "
185
			+ "    <source type=\"ESI\"></source>                                 "
186
			+ "    <detector type=\"EM\"></detector>                              "
187
			+ "  </instrument>                                                    "
188
			+ "</inline>                                                          ";
189

    
190
	/*
191
	 * Retrus an access block base on params passed and the defaul perm order -
192
	 * allow first
193
	 */
194
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
195
			boolean write, boolean changePermission, boolean all) {
196
		return getAccessBlock(principal, grantAccess, read, write, changePermission, all,
197
				ALLOWFIRST);
198
	}
199

    
200
	/**
201
	 * This function returns an access block based on the params passed
202
	 */
203
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
204
			boolean write, boolean changePermission, boolean all, String permOrder) {
205
		String accessBlock = "<access "
206
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
207
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
208

    
209
		accessBlock += generateOneAccessRule(principal, grantAccess, read, write,
210
				changePermission, all);
211
		accessBlock += "</access>";
212

    
213
		return accessBlock;
214

    
215
	}
216

    
217
	/*
218
	 * Gets eml access block base on given acccess rules and perm order
219
	 */
220
	protected String getAccessBlock(Vector<String> accessRules, String permOrder) {
221
		String accessBlock = "<access "
222
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
223
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
224
		// adding rules
225
		if (accessRules != null && !accessRules.isEmpty()) {
226
			for (int i = 0; i < accessRules.size(); i++) {
227
				String rule = (String) accessRules.elementAt(i);
228
				accessBlock += rule;
229

    
230
			}
231
		}
232
		accessBlock += "</access>";
233
		return accessBlock;
234
	}
235

    
236
	/*
237
	 * Generates a access rule for given parameter. Note this xml portion
238
	 * doesn't include <access></access>
239
	 */
240
	protected String generateOneAccessRule(String principal, boolean grantAccess,
241
			boolean read, boolean write, boolean changePermission, boolean all) {
242
		String accessBlock = "";
243

    
244
		if (grantAccess) {
245
			accessBlock = "<allow>";
246
		} else {
247
			accessBlock = "<deny>";
248
		}
249

    
250
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
251

    
252
		if (all) {
253
			accessBlock += "<permission>all</permission>";
254
		} else {
255
			if (read) {
256
				accessBlock += "<permission>read</permission>";
257
			}
258
			if (write) {
259
				accessBlock += "<permission>write</permission>";
260
			}
261
			if (changePermission) {
262
				accessBlock += "<permission>changePermission</permission>";
263
			}
264
		}
265

    
266
		if (grantAccess) {
267
			accessBlock += "</allow>";
268
		} else {
269
			accessBlock += "</deny>";
270
		}
271
		return accessBlock;
272

    
273
	}
274
	
275
    /**
276
     * This function returns a valid eml document with public read access
277
     */
278
    protected String getTestEmlDoc(String title, String emlVersion) {
279

    
280
        String testDocument = "";
281

    
282
        String header;
283
		if (emlVersion == EML2_0_1) {
284
			header = testEml_201_Header;
285
		} else if (emlVersion == EML2_1_0) {
286
			header = testEml_210_Header;
287
		} else { // if (emlVersion == EML2_1_1) {
288
			header = testEml_211_Header;
289
		}
290
        
291
        testDocument += header;
292
        
293
        // if this is an EML 2.1.0 or later document, the document level access is
294
        // before the dataset element.
295
        if (emlVersion == EML2_1_0 || emlVersion == EML2_1_1) {
296
        	testDocument += getAccessBlock("public", true, true, false, false, false);
297
        }
298
        testDocument += "<dataset scope=\"document\"><title>" + title + "</title>"
299
				+ testEmlCreatorBlock;
300

    
301
        testDocument += testEmlContactBlock;
302
        
303
        // if this is an EML 2.0.1 or earlier document, the document level access is
304
        // inside the dataset element.
305
        if (emlVersion != EML2_1_0 && emlVersion != EML2_1_1) {
306
        	testDocument += getAccessBlock("public", true, true, false, false, false);
307
        }
308
        testDocument += "</dataset>";
309
        testDocument += "</eml:eml>";
310

    
311
        return testDocument;
312
    }
313

    
314
	/**
315
	 * This function returns a valid eml document with no access rules 
316
	 */
317
	protected String getTestEmlDoc(String title, String emlVersion, String inlineData1,
318
			String inlineData2, String onlineUrl1, String onlineUrl2,
319
			String docAccessBlock, String inlineAccessBlock1, String inlineAccessBlock2,
320
			String onlineAccessBlock1, String onlineAccessBlock2) {
321

    
322
		debug("getTestEmlDoc(): title=" + title + " inlineData1=" + inlineData1
323
				+ " inlineData2=" + inlineData2 + " onlineUrl1=" + onlineUrl1
324
				+ " onlineUrl2=" + onlineUrl2 + " docAccessBlock=" + docAccessBlock
325
				+ " inlineAccessBlock1=" + inlineAccessBlock1 + " inlineAccessBlock2="
326
				+ inlineAccessBlock2 + " onlineAccessBlock1=" + onlineAccessBlock1
327
				+ " onlineAccessBlock2=" + onlineAccessBlock2);
328
		String testDocument = "";
329
		String header;
330
		if (emlVersion == EML2_0_0) {
331
			header = testEml_200_Header;
332
		} else if (emlVersion == EML2_0_1) {
333
			header = testEml_201_Header;
334
		} else if (emlVersion == EML2_1_0) {
335
			header = testEml_210_Header;
336
		} else { // if (emlVersion == EML2_1_1) {
337
			header = testEml_211_Header;
338
		}
339
		testDocument += header;
340
		
341
		// if this is a 2.1.0+ document, the document level access block sits
342
		// at the same level and before the dataset element.
343
		if (docAccessBlock != null && (emlVersion.equals(EML2_1_0) || emlVersion.equals(EML2_1_1))) {
344
			testDocument += docAccessBlock;
345
		}
346
		
347
		testDocument += "<dataset scope=\"document\"><title>"
348
				+ title + "</title>" + testEmlCreatorBlock;
349

    
350
		if (inlineData1 != null) {
351
			testDocument = testDocument
352
					+ "<distribution scope=\"document\" id=\"inlineEntity1\">"
353
					+ inlineData1 + "</distribution>";
354
		}
355
		if (inlineData2 != null) {
356
			testDocument = testDocument
357
					+ "<distribution scope=\"document\" id=\"inlineEntity2\">"
358
					+ inlineData2 + "</distribution>";
359
		}
360
		if (onlineUrl1 != null) {
361
			testDocument = testDocument
362
					+ "<distribution scope=\"document\" id=\"onlineEntity1\">"
363
					+ "<online><url function=\"download\">" + onlineUrl1
364
					+ "</url></online></distribution>";
365
		}
366
		if (onlineUrl2 != null) {
367
			testDocument = testDocument
368
					+ "<distribution scope=\"document\" id=\"onlineEntity2\">"
369
					+ "<online><url function=\"download\">" + onlineUrl2
370
					+ "</url></online></distribution>";
371
		}
372
		testDocument += testEmlContactBlock;
373

    
374
		// if this is a 2.0.X document, the document level access block sits
375
		// inside the dataset element.
376
		if (docAccessBlock != null && 
377
				(emlVersion.equals(EML2_0_0) || emlVersion.equals(EML2_0_1))) {
378
			testDocument += docAccessBlock;
379
		}
380

    
381
		testDocument += "</dataset>";
382

    
383
		if (inlineAccessBlock1 != null) {
384
			testDocument += "<additionalMetadata>";
385
			testDocument += "<describes>inlineEntity1</describes>";
386
			testDocument += inlineAccessBlock1;
387
			testDocument += "</additionalMetadata>";
388
		}
389

    
390
		if (inlineAccessBlock2 != null) {
391
			testDocument += "<additionalMetadata>";
392
			testDocument += "<describes>inlineEntity2</describes>";
393
			testDocument += inlineAccessBlock2;
394
			testDocument += "</additionalMetadata>";
395
		}
396

    
397
		if (onlineAccessBlock1 != null) {
398
			testDocument += "<additionalMetadata>";
399
			testDocument += "<describes>onlineEntity1</describes>";
400
			testDocument += onlineAccessBlock1;
401
			testDocument += "</additionalMetadata>";
402
		}
403

    
404
		if (onlineAccessBlock2 != null) {
405
			testDocument += "<additionalMetadata>";
406
			testDocument += "<describes>onlineEntity2</describes>";
407
			testDocument += onlineAccessBlock2;
408
			testDocument += "</additionalMetadata>";
409
		}
410

    
411
		testDocument += "</eml:eml>";
412

    
413
		// System.out.println("Returning following document" + testDocument);
414
		return testDocument;
415
	}
416
	
417
	/**
418
	 * 
419
	 */
420
	protected String getTestDocFromFile(String filePath) throws IOException{
421
		StringBuffer output = new StringBuffer();
422
		
423
		FileReader fileReader = new FileReader(new File(filePath));
424
		BufferedReader bufferedReader = new BufferedReader(fileReader);
425
		String readLine = null;
426
		
427
		while ((readLine = bufferedReader.readLine()) != null) {
428
			output.append(readLine);
429
		}
430
		
431
		return output.toString();
432
	}
433

    
434
	
435
    /**
436
     * Constructor to build the test
437
     */
438
    public MCTestCase() {
439
        super();
440
    }
441
	
442
    /**
443
     * Constructor to build the test
444
     *
445
     * @param name the name of the test method
446
     */
447
    public MCTestCase(String name) {
448
        super(name);
449
    }
450
    
451
	/**
452
	 * Establish a testing framework by initializing appropriate objects
453
	 */
454
	protected void setUp() throws Exception {
455
		try {
456
			if (metacatConnectionNeeded) {
457
				debug("setUp() - Testing Metacat Url: " + metacatUrl);
458
				m = MetacatFactory.createMetacatConnection(metacatUrl);
459
			}
460
		} catch (MetacatInaccessibleException mie) {
461
			System.err.println("Metacat is: " + metacatUrl);
462
			fail("Metacat connection failed." + mie.getMessage());
463
		}
464
	}
465
    
466
    protected static void debug(String debugMessage) {
467
    	if (printDebug) {
468
    		System.err.println(debugMessage);
469
    	}
470
    }
471
    
472
	protected static Vector<Hashtable<String, Object>> dbSelect(String sqlStatement,
473
			String methodName) throws SQLException {
474
		Vector<Hashtable<String, Object>> resultVector = new Vector<Hashtable<String, Object>>();
475

    
476
		DBConnectionPool connPool = DBConnectionPool.getInstance();
477
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
478
		int serialNumber = dbconn.getCheckOutSerialNumber();
479

    
480
		PreparedStatement pstmt = null;
481

    
482
		debug("Selecting from db: " + sqlStatement);
483
		pstmt = dbconn.prepareStatement(sqlStatement);
484
		pstmt.execute();
485

    
486
		ResultSet resultSet = pstmt.getResultSet();
487
		ResultSetMetaData rsMetaData = resultSet.getMetaData();
488
		int numColumns = rsMetaData.getColumnCount();
489
		debug("Number of data columns: " + numColumns);
490
		while (resultSet.next()) {
491
			Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
492
			for (int i = 1; i <= numColumns; i++) {
493
				if (resultSet.getObject(i) != null) {
494
					hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i));
495
				}
496
			}
497
			debug("adding data row to result vector");
498
			resultVector.add(hashTable);
499
		}
500

    
501
		resultSet.close();
502
		pstmt.close();
503
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
504

    
505
		return resultVector;
506
	}
507
	
508
	protected static void dbQuery(String sqlStatement, String methodName)
509
			throws SQLException {
510

    
511
		DBConnectionPool connPool = DBConnectionPool.getInstance();
512
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
513
		int serialNumber = dbconn.getCheckOutSerialNumber();
514

    
515
		Statement statement = dbconn.createStatement();
516

    
517
		debug("Executing against db: " + sqlStatement);
518
		statement.executeQuery(sqlStatement);
519

    
520
		statement.close();
521
		
522
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
523
	}
524
	
525
	protected static void dbUpdate(String sqlStatement, String methodName)
526
			throws SQLException {
527

    
528
		DBConnectionPool connPool = DBConnectionPool.getInstance();
529
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
530
		int serialNumber = dbconn.getCheckOutSerialNumber();
531

    
532
		Statement statement = dbconn.createStatement();
533

    
534
		debug("Executing against db: " + sqlStatement);
535
		statement.executeUpdate(sqlStatement);
536

    
537
		statement.close();
538

    
539
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
540
	}
541
	
542
	protected static void httpPost(String url, HashMap<String,String> paramMap) throws Exception {
543
		debug("Posting to: " + url);
544
		if (httpClient == null) {
545
			httpClient = new DefaultHttpClient();
546
		}
547
		String postResponse = RequestUtil.post(httpClient, url, paramMap);
548
		debug("Post response: " + postResponse);
549
		if (postResponse.contains("<error>")) {
550
			fail("Error posting to metacat: " + postResponse);
551
		}
552
	}
553
	
554
	protected static void resetHttpClient() {
555
		httpClient = null;
556
	}
557
	
558
	/**
559
	 * Create a unique docid for testing insert and update. Does not
560
	 * include the 'revision' part of the id.
561
	 * 
562
	 * @return a String docid based on the current date and time
563
	 */
564
	protected String generateDocumentId() {
565
		try {
566
			Thread.sleep(1010);
567
		} catch (InterruptedException ie) {
568
			debug("Could not sleep: " + ie.getMessage());
569
		}
570

    
571
		return DocumentUtil.generateDocumentId(prefix, 0);
572
	}
573
	
574
	/**
575
	 * Insert a document into metacat. The expected result is passed as result
576
	 */
577
	protected String insertDocumentId(String docid, String docText, boolean result,
578
			boolean expectKarmaException) {
579
		debug("insertDocumentId() - docid=" + docid + " expectedResult=" + result
580
				+ " expectKarmaException=" + expectKarmaException);
581
		String response = null;
582
		try {
583
			response = m.insert(docid, new StringReader(docText), null);
584
			if (result) {
585
				assertTrue(response, (response.indexOf("<success>") != -1));
586
				assertTrue(response, response.indexOf(docid) != -1);
587
			} else {
588
				assertTrue(response, (response.indexOf("<success>") == -1));
589
			}
590
			debug("insertDocid():  response=" + response);
591
		} catch (MetacatInaccessibleException mie) {
592
			fail("Metacat Inaccessible:\n" + mie.getMessage());
593
		} catch (InsufficientKarmaException ike) {
594
			if (!expectKarmaException) {
595
				fail("Insufficient karma:\n" + ike.getMessage());
596
			}
597
		} catch (MetacatException me) {
598
			fail("Metacat Error:\n" + me.getMessage());
599
		} catch (Exception e) {
600
			fail("General exception:\n" + e.getMessage());
601
		}
602
		return response;
603
	}
604

    
605
	/**
606
	 * Insert a document into metacat. The expected result is passed as result
607
	 */
608

    
609
	protected String uploadDocumentId(String docid, String filePath, boolean result,
610
			boolean expectedKarmaException) {
611
		debug("uploadDocumentId() - docid=" + docid + " filePath=" + filePath
612
				+ " expectedResult=" + result + " expectedKarmaException="
613
				+ expectedKarmaException);
614
		String response = null;
615
		try {
616
			response = m.upload(docid, new File(filePath));
617
			if (result) {
618
				assertTrue(response, (response.indexOf("<success>") != -1));
619
				assertTrue(response, response.indexOf(docid) != -1);
620
			} else {
621
				assertTrue(response, (response.indexOf("<success>") == -1));
622
			}
623
			debug("uploadDocid():  response=" + response);
624
		} catch (MetacatInaccessibleException mie) {
625
			fail("Metacat Inaccessible:\n" + mie.getMessage());
626
		} catch (InsufficientKarmaException ike) {
627
			if (!expectedKarmaException) {
628
				fail("Insufficient karma:\n" + ike.getMessage());
629
			}
630
		} catch (MetacatException me) {
631
			if (result) {
632
				fail("Metacat Error:\n" + me.getMessage());
633
			} else {
634
				debug("Metacat Error:\n" + me.getMessage());
635
			}
636
		} catch (Exception e) {
637
			fail("General exception:\n" + e.getMessage());
638
		}
639
		return response;
640
	}
641

    
642
	/**
643
	 * Update a document in metacat. The expected result is passed as result
644
	 */
645
	protected String updateDocumentId(String docid, String docText, boolean result,
646
			boolean expectedKarmaFailure) {
647
		debug("updateDocumentId() - docid=" + docid + " expectedResult=" + result
648
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
649
		String response = null;
650
		try {
651
			response = m.update(docid, new StringReader(testdocument), null);
652
			debug("updateDocumentId() - response=" + response);
653
			
654
			if (result) {
655
				assertTrue(response, (response.indexOf("<success>") != -1));
656
				assertTrue(response, response.indexOf(docid) != -1);
657
			} else {
658
				assertTrue(response, (response.indexOf("<success>") == -1));
659
			}			
660
		} catch (MetacatInaccessibleException mie) {
661
			fail("Metacat Inaccessible:\n" + mie.getMessage());
662
		} catch (InsufficientKarmaException ike) {
663
			if (!expectedKarmaFailure) {
664
				fail("Insufficient karma:\n" + ike.getMessage());
665
			}
666
		} catch (MetacatException me) {
667
			if (result) {
668
				fail("Metacat Error:\n" + me.getMessage());
669
			} else {
670
				debug("Metacat Error:\n" + me.getMessage());
671
			}
672
		} catch (Exception e) {
673
			fail("General exception:\n" + e.getMessage());
674
		}
675

    
676
		return response;
677
	}
678

    
679
	/**
680
	 * Delete a document into metacat. The expected result is passed as result
681
	 */
682
	protected void deleteDocumentId(String docid, boolean result, boolean expectedKarmaFailure) {
683
		debug("deleteDocumentId() - docid=" + docid + " expectedResult=" + result
684
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
685
		try {
686
			Thread.sleep(5000);
687
			String response = m.delete(docid);
688
			debug("deleteDocumentId() -  response=" + response);
689
			
690
			if (result) {
691
				assertTrue(response, response.indexOf("<success>") != -1);
692
			} else {
693
				assertTrue(response, response.indexOf("<success>") == -1);
694
			}
695
		} catch (MetacatInaccessibleException mie) {
696
			fail("Metacat Inaccessible:\n" + mie.getMessage());
697
		} catch (InsufficientKarmaException ike) {
698
			if (!expectedKarmaFailure) {
699
				fail("Insufficient karma:\n" + ike.getMessage());
700
			}
701
		} catch (MetacatException me) {
702
			if (result) {
703
				fail("Metacat Error:\n" + me.getMessage());
704
			} else {
705
				debug("Metacat Error:\n" + me.getMessage());
706
			}
707
		} catch (Exception e) {
708
			fail("General exception:\n" + e.getMessage());
709
		}
710
	}
711
	
712
	/**
713
	 * Read a document from metacat and check if it is equal to a given string.
714
	 * The expected result is passed as result
715
	 */
716
	protected void readDocumentIdWhichEqualsDoc(String docid, String testDoc, boolean result,
717
			boolean expectedKarmaFailure) {
718
		debug("readDocumentIdWhichEqualsDoc() - docid=" + docid + " expectedResult=" + result
719
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
720
		try {
721
			Reader r = new InputStreamReader(m.read(docid));
722
			String doc = IOUtil.getAsString(r, true);
723
			debug("readDocumentIdWhichEqualsDoc() -  doc=" + doc);
724
			
725
			if (result) {
726

    
727
				if (!testDoc.equals(doc)) {
728
					System.out.println("doc ***********************");
729
					System.out.println(doc);
730
					System.out.println("end doc ***********************");
731
					System.out.println("testDoc ***********************");
732
					System.out.println(testDoc);
733
					System.out.println("end testDoc ***********************");
734
				}
735

    
736
				assertTrue(testDoc.equals(doc));
737
			} else {
738
				assertTrue(doc.indexOf("<error>") != -1);
739
			}
740
		} catch (MetacatInaccessibleException mie) {
741
			fail("Metacat Inaccessible:\n" + mie.getMessage());
742
		} catch (InsufficientKarmaException ike) {
743
			if (!expectedKarmaFailure) {
744
				fail("Insufficient karma:\n" + ike.getMessage());
745
			}
746
		} catch (MetacatException me) {
747
			fail("Metacat Error:\n" + me.getMessage());
748
		} catch (Exception e) {
749
			fail("General exception:\n" + e.getMessage());
750
		}
751

    
752
	}
753

    
754
}
    (1-1/1)