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: 2013-07-31 23:34:34 -0700 (Wed, 31 Jul 2013) $'
9
 * '$Revision: 8099 $'
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 java.io.BufferedReader;
29
import java.io.File;
30
import java.io.FileReader;
31
import java.io.IOException;
32
import java.io.InputStreamReader;
33
import java.io.Reader;
34
import java.io.StringReader;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.ResultSetMetaData;
38
import java.sql.SQLException;
39
import java.util.HashMap;
40
import java.util.Hashtable;
41
import java.util.Vector;
42

    
43
import junit.framework.TestCase;
44

    
45
import org.apache.http.client.HttpClient;
46
import org.apache.http.impl.client.DefaultHttpClient;
47

    
48
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
49
import edu.ucsb.nceas.metacat.client.Metacat;
50
import edu.ucsb.nceas.metacat.client.MetacatException;
51
import edu.ucsb.nceas.metacat.client.MetacatFactory;
52
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
53
import edu.ucsb.nceas.metacat.database.DBConnection;
54
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
55
import edu.ucsb.nceas.metacat.properties.PropertyService;
56
import edu.ucsb.nceas.metacat.shared.ServiceException;
57
import edu.ucsb.nceas.metacat.util.DocumentUtil;
58
import edu.ucsb.nceas.metacat.util.RequestUtil;
59
import edu.ucsb.nceas.utilities.IOUtil;
60
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
61
import edu.ucsb.nceas.utilities.SortedProperties;
62

    
63
/**
64
 * A base JUnit class for Metacat tests
65
 */
66
public class MCTestCase
67
    extends TestCase {
68
	
69
    private static boolean printDebug = false;
70
    
71
	protected static String EML2_0_0 = "EML2_0_0";
72
	protected static String EML2_0_1 = "EML2_0_1";
73
	protected static String EML2_1_0 = "EML2_1_0";
74
	protected static String EML2_1_1 = "EML2_1_1";
75

    
76
	
77
	protected boolean SUCCESS = true;
78
	protected boolean FAILURE = false;
79
	
80
	protected static final String ALLOWFIRST = "allowFirst";
81
	protected static final String DENYFIRST = "denyFirst";
82
	
83
	protected String testdatadir = "test/clienttestfiles/";
84
	protected String prefix = "test";
85
	protected String testdocument = "";
86
	
87
	protected static HttpClient httpClient = null;
88
	
89
	protected static boolean metacatConnectionNeeded = false;
90
	protected Metacat m;
91

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

    
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
		} catch (IOException ioe) {
117
			System.err.println("Could not read property file in static block: " 
118
					+ ioe.getMessage());
119
		} 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
	
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
	
150
	protected String testEml_211_Header = "<?xml version=\"1.0\"?><eml:eml"
151
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.1\""
152
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
153
		+ " packageId=\"eml.1.1\" system=\"knb\""
154
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.1 eml.xsd\""
155
		+ " scope=\"system\">";
156

    
157
	protected String testEmlCreatorBlock = "<creator scope=\"document\">                                       "
158
			+ " <individualName>                                                  "
159
			+ "    <surName>Smith</surName>                                       "
160
			+ " </individualName>                                                 "
161
			+ "</creator>                                                         ";
162

    
163
	protected String testEmlContactBlock = "<contact scope=\"document\">                                       "
164
			+ " <individualName>                                                  "
165
			+ "    <surName>Jackson</surName>                                     "
166
			+ " </individualName>                                                 "
167
			+ "</contact>                                                         ";
168

    
169
	protected String testEmlInlineBlock1 = "<inline>                                                           "
170
			+ "  <admin>                                                          "
171
			+ "    <contact>                                                      "
172
			+ "      <name>Operator</name>                                        "
173
			+ "      <institution>PSI</institution>                               "
174
			+ "    </contact>                                                     "
175
			+ "  </admin>                                                         "
176
			+ "</inline>                                                          ";
177

    
178
	protected String testEmlInlineBlock2 = "<inline>                                                           "
179
			+ "  <instrument>                                                     "
180
			+ "    <instName>LCQ</instName>                                       "
181
			+ "    <source type=\"ESI\"></source>                                 "
182
			+ "    <detector type=\"EM\"></detector>                              "
183
			+ "  </instrument>                                                    "
184
			+ "</inline>                                                          ";
185

    
186
    
187
    /**
188
     * Returns an xml squery that searches for the doc id in the
189
     * title of documents. This function is for eml-2.0.1+ only. For 
190
     * other eml versions, this function might have to modified.
191
     */
192
    protected String getTestEmlQuery(String titlePart, String emlVersion) {
193

    
194
    	String docType;
195
    	if (emlVersion.equals(EML2_0_1)) {
196
    		docType = "eml://ecoinformatics.org/eml-2.0.1";
197
    	} else if (emlVersion.equals(EML2_1_0)) {
198
    		docType = "eml://ecoinformatics.org/eml-2.1.0";
199
    	} else { //if (emlVersion.equals(EML2_1_1)) {
200
    		docType = "eml://ecoinformatics.org/eml-2.1.1";
201
    	}
202
    	
203
        String sQuery = "";
204
        sQuery = 
205
        	"<pathquery version=\"1.0\">" +
206
        		"<meta_file_id>unspecified</meta_file_id>" +
207
        		"<querytitle>unspecified</querytitle>" + 
208
        		"<returnfield>dataset/title</returnfield>" +
209
        		"<returndoctype>" + docType + "</returndoctype>" +
210
        		"<querygroup operator=\"UNION\">" +
211
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
212
        				"<value>" + titlePart + "</value>" +
213
        				"<pathexpr>dataset/title</pathexpr>" +
214
        			"</queryterm>" +
215
        		"</querygroup>" +
216
        	"</pathquery>";
217

    
218
        return sQuery;
219
    }
220
	
221
	/**
222
     * Query a document by looking for a part of the title in the title element.
223
     * Then check if the testTitle exists in the doc.
224
     * @param titlePart the part of the title of the doc to look for
225
     * @param testTitle the title containing special characters
226
     * @param result are we expecting SUCCESS or FAILURE
227
     * @param expextedKarmaFailure
228
     */
229
    protected void queryDocWhichHasTitle(String titlePart, String testTitle,
230
                                         String emlVersion, boolean result) {
231
        try {
232
            String sQuery = getTestEmlQuery(titlePart, emlVersion);
233
        	Reader queryReader = new StringReader(sQuery);
234
            Reader resultReader = m.query(queryReader);
235
            String queryResult = IOUtil.getAsString(resultReader, true);
236
            if (result) {
237
                if (!queryResult.contains(testTitle)) {
238
                    debug("queryResult: " + queryResult);
239
                    debug("does not contain title: " + testTitle);
240
                }
241

    
242
                assertTrue(queryResult.contains(testTitle));
243
            }
244
            else {
245
                assertTrue(queryResult.indexOf("<error>") != -1);
246
            }
247
        }
248
        catch (MetacatInaccessibleException mie) {
249
            fail("Metacat Inaccessible:\n" + mie.getMessage());
250
        }
251
        catch (Exception e) {
252
            fail("General exception:\n" + e.getMessage());
253
        }
254

    
255
    }
256
	
257
	/*
258
	 * Retrus an access block base on params passed and the defaul perm order -
259
	 * allow first
260
	 */
261
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
262
			boolean write, boolean changePermission, boolean all) {
263
		return getAccessBlock(principal, grantAccess, read, write, changePermission, all,
264
				ALLOWFIRST);
265
	}
266

    
267
	/**
268
	 * This function returns an access block based on the params passed
269
	 */
270
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
271
			boolean write, boolean changePermission, boolean all, String permOrder) {
272
		String accessBlock = "<access "
273
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
274
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
275

    
276
		accessBlock += generateOneAccessRule(principal, grantAccess, read, write,
277
				changePermission, all);
278
		accessBlock += "</access>";
279

    
280
		return accessBlock;
281

    
282
	}
283

    
284
	/*
285
	 * Gets eml access block base on given acccess rules and perm order
286
	 */
287
	protected String getAccessBlock(Vector<String> accessRules, String permOrder) {
288
		String accessBlock = "<access "
289
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
290
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
291
		// adding rules
292
		if (accessRules != null && !accessRules.isEmpty()) {
293
			for (int i = 0; i < accessRules.size(); i++) {
294
				String rule = (String) accessRules.elementAt(i);
295
				accessBlock += rule;
296

    
297
			}
298
		}
299
		accessBlock += "</access>";
300
		return accessBlock;
301
	}
302

    
303
	/*
304
	 * Generates a access rule for given parameter. Note this xml portion
305
	 * doesn't include <access></access>
306
	 */
307
	protected String generateOneAccessRule(String principal, boolean grantAccess,
308
			boolean read, boolean write, boolean changePermission, boolean all) {
309
		String accessBlock = "";
310

    
311
		if (grantAccess) {
312
			accessBlock = "<allow>";
313
		} else {
314
			accessBlock = "<deny>";
315
		}
316

    
317
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
318

    
319
		if (all) {
320
			accessBlock += "<permission>all</permission>";
321
		} else {
322
			if (read) {
323
				accessBlock += "<permission>read</permission>";
324
			}
325
			if (write) {
326
				accessBlock += "<permission>write</permission>";
327
			}
328
			if (changePermission) {
329
				accessBlock += "<permission>changePermission</permission>";
330
			}
331
		}
332

    
333
		if (grantAccess) {
334
			accessBlock += "</allow>";
335
		} else {
336
			accessBlock += "</deny>";
337
		}
338
		return accessBlock;
339

    
340
	}
341
	
342
    /**
343
     * This function returns a valid eml document with public read access
344
     */
345
    protected String getTestEmlDoc(String title, String emlVersion) {
346

    
347
        String testDocument = "";
348

    
349
        String header;
350
		if (emlVersion == EML2_0_1) {
351
			header = testEml_201_Header;
352
		} else if (emlVersion == EML2_1_0) {
353
			header = testEml_210_Header;
354
		} else { // if (emlVersion == EML2_1_1) {
355
			header = testEml_211_Header;
356
		}
357
        
358
        testDocument += header;
359
        
360
        // if this is an EML 2.1.0 or later document, the document level access is
361
        // before the dataset element.
362
        if (emlVersion == EML2_1_0 || emlVersion == EML2_1_1) {
363
        	testDocument += getAccessBlock("public", true, true, false, false, false);
364
        }
365
        testDocument += "<dataset scope=\"document\"><title>" + title + "</title>"
366
				+ testEmlCreatorBlock;
367

    
368
        testDocument += testEmlContactBlock;
369
        
370
        // if this is an EML 2.0.1 or earlier document, the document level access is
371
        // inside the dataset element.
372
        if (emlVersion != EML2_1_0 && emlVersion != EML2_1_1) {
373
        	testDocument += getAccessBlock("public", true, true, false, false, false);
374
        }
375
        testDocument += "</dataset>";
376
        testDocument += "</eml:eml>";
377

    
378
        return testDocument;
379
    }
380

    
381
	/**
382
	 * This function returns a valid eml document with no access rules 
383
	 */
384
	protected String getTestEmlDoc(String title, String emlVersion, String inlineData1,
385
			String inlineData2, String onlineUrl1, String onlineUrl2,
386
			String docAccessBlock, String inlineAccessBlock1, String inlineAccessBlock2,
387
			String onlineAccessBlock1, String onlineAccessBlock2) {
388

    
389
		debug("getTestEmlDoc(): title=" + title + " inlineData1=" + inlineData1
390
				+ " inlineData2=" + inlineData2 + " onlineUrl1=" + onlineUrl1
391
				+ " onlineUrl2=" + onlineUrl2 + " docAccessBlock=" + docAccessBlock
392
				+ " inlineAccessBlock1=" + inlineAccessBlock1 + " inlineAccessBlock2="
393
				+ inlineAccessBlock2 + " onlineAccessBlock1=" + onlineAccessBlock1
394
				+ " onlineAccessBlock2=" + onlineAccessBlock2);
395
		String testDocument = "";
396
		String header;
397
		if (emlVersion == EML2_0_0) {
398
			header = testEml_200_Header;
399
		} else if (emlVersion == EML2_0_1) {
400
			header = testEml_201_Header;
401
		} else if (emlVersion == EML2_1_0) {
402
			header = testEml_210_Header;
403
		} else { // if (emlVersion == EML2_1_1) {
404
			header = testEml_211_Header;
405
		}
406
		testDocument += header;
407
		
408
		// if this is a 2.1.0+ document, the document level access block sits
409
		// at the same level and before the dataset element.
410
		if (docAccessBlock != null && (emlVersion.equals(EML2_1_0) || emlVersion.equals(EML2_1_1))) {
411
			testDocument += docAccessBlock;
412
		}
413
		
414
		testDocument += "<dataset scope=\"document\"><title>"
415
				+ title + "</title>" + testEmlCreatorBlock;
416

    
417
		if (inlineData1 != null) {
418
			testDocument = testDocument
419
					+ "<distribution scope=\"document\" id=\"inlineEntity1\">"
420
					+ inlineData1 + "</distribution>";
421
		}
422
		if (inlineData2 != null) {
423
			testDocument = testDocument
424
					+ "<distribution scope=\"document\" id=\"inlineEntity2\">"
425
					+ inlineData2 + "</distribution>";
426
		}
427
		if (onlineUrl1 != null) {
428
			testDocument = testDocument
429
					+ "<distribution scope=\"document\" id=\"onlineEntity1\">"
430
					+ "<online><url function=\"download\">" + onlineUrl1
431
					+ "</url></online></distribution>";
432
		}
433
		if (onlineUrl2 != null) {
434
			testDocument = testDocument
435
					+ "<distribution scope=\"document\" id=\"onlineEntity2\">"
436
					+ "<online><url function=\"download\">" + onlineUrl2
437
					+ "</url></online></distribution>";
438
		}
439
		testDocument += testEmlContactBlock;
440

    
441
		// if this is a 2.0.X document, the document level access block sits
442
		// inside the dataset element.
443
		if (docAccessBlock != null && 
444
				(emlVersion.equals(EML2_0_0) || emlVersion.equals(EML2_0_1))) {
445
			testDocument += docAccessBlock;
446
		}
447

    
448
		testDocument += "</dataset>";
449

    
450
		if (inlineAccessBlock1 != null) {
451
			testDocument += "<additionalMetadata>";
452
			testDocument += "<describes>inlineEntity1</describes>";
453
			testDocument += inlineAccessBlock1;
454
			testDocument += "</additionalMetadata>";
455
		}
456

    
457
		if (inlineAccessBlock2 != null) {
458
			testDocument += "<additionalMetadata>";
459
			testDocument += "<describes>inlineEntity2</describes>";
460
			testDocument += inlineAccessBlock2;
461
			testDocument += "</additionalMetadata>";
462
		}
463

    
464
		if (onlineAccessBlock1 != null) {
465
			testDocument += "<additionalMetadata>";
466
			testDocument += "<describes>onlineEntity1</describes>";
467
			testDocument += onlineAccessBlock1;
468
			testDocument += "</additionalMetadata>";
469
		}
470

    
471
		if (onlineAccessBlock2 != null) {
472
			testDocument += "<additionalMetadata>";
473
			testDocument += "<describes>onlineEntity2</describes>";
474
			testDocument += onlineAccessBlock2;
475
			testDocument += "</additionalMetadata>";
476
		}
477

    
478
		testDocument += "</eml:eml>";
479

    
480
		// System.out.println("Returning following document" + testDocument);
481
		return testDocument;
482
	}
483
	
484
	/**
485
	 * 
486
	 */
487
	protected String getTestDocFromFile(String filePath) throws IOException{
488
		StringBuffer output = new StringBuffer();
489
		
490
		FileReader fileReader = new FileReader(new File(filePath));
491
		BufferedReader bufferedReader = new BufferedReader(fileReader);
492
		String readLine = null;
493
		
494
		while ((readLine = bufferedReader.readLine()) != null) {
495
			output.append(readLine);
496
		}
497
		
498
		return output.toString();
499
	}
500

    
501
	
502
    /**
503
     * Constructor to build the test
504
     */
505
    public MCTestCase() {
506
        super();
507
    }
508
	
509
    /**
510
     * Constructor to build the test
511
     *
512
     * @param name the name of the test method
513
     */
514
    public MCTestCase(String name) {
515
        super(name);
516
    }
517
    
518
	/**
519
	 * Establish a testing framework by initializing appropriate objects
520
	 */
521
	protected void setUp() throws Exception {
522
		try {
523
			if (metacatConnectionNeeded) {
524
				debug("setUp() - Testing Metacat Url: " + metacatUrl);
525
				m = MetacatFactory.createMetacatConnection(metacatUrl);
526
			}
527
		} catch (MetacatInaccessibleException mie) {
528
			System.err.println("Metacat is: " + metacatUrl);
529
			fail("Metacat connection failed." + mie.getMessage());
530
		}
531
	}
532
    
533
    protected static void debug(String debugMessage) {
534
    	if (printDebug) {
535
    		System.err.println(debugMessage);
536
    	}
537
    }
538
    
539
	protected static Vector<Hashtable<String, Object>> dbSelect(String sqlStatement,
540
			String methodName) throws SQLException {
541
		Vector<Hashtable<String, Object>> resultVector = new Vector<Hashtable<String, Object>>();
542

    
543
		DBConnectionPool connPool = DBConnectionPool.getInstance();
544
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
545
		int serialNumber = dbconn.getCheckOutSerialNumber();
546

    
547
		PreparedStatement pstmt = null;
548

    
549
		debug("Selecting from db: " + sqlStatement);
550
		pstmt = dbconn.prepareStatement(sqlStatement);
551
		pstmt.execute();
552

    
553
		ResultSet resultSet = pstmt.getResultSet();
554
		ResultSetMetaData rsMetaData = resultSet.getMetaData();
555
		int numColumns = rsMetaData.getColumnCount();
556
		debug("Number of data columns: " + numColumns);
557
		while (resultSet.next()) {
558
			Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
559
			for (int i = 1; i <= numColumns; i++) {
560
				if (resultSet.getObject(i) != null) {
561
					hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i));
562
				}
563
			}
564
			debug("adding data row to result vector");
565
			resultVector.add(hashTable);
566
		}
567

    
568
		resultSet.close();
569
		pstmt.close();
570
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
571

    
572
		return resultVector;
573
	}
574
	
575
	protected static void dbQuery(String sqlStatement, String methodName)
576
			throws SQLException {
577

    
578
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
579
		int serialNumber = dbconn.getCheckOutSerialNumber();
580

    
581
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
582
		debug("Executing against db: " + sqlStatement);
583
		statement.executeQuery();
584

    
585
		statement.close();
586
		
587
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
588
	}
589
	
590
	protected static void dbUpdate(String sqlStatement, String methodName)
591
			throws SQLException {
592

    
593
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
594
		int serialNumber = dbconn.getCheckOutSerialNumber();
595

    
596
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
597
		debug("Executing against db: " + sqlStatement);
598
		statement.executeUpdate();
599
		statement.close();
600

    
601
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
602
	}
603
	
604
	protected static void httpPost(String url, HashMap<String,String> paramMap) throws Exception {
605
		debug("Posting to: " + url);
606
		if (httpClient == null) {
607
			httpClient = new DefaultHttpClient();
608
		}
609
		String postResponse = RequestUtil.post(httpClient, url, paramMap);
610
		debug("Post response: " + postResponse);
611
		if (postResponse.contains("<error>")) {
612
			fail("Error posting to metacat: " + postResponse);
613
		}
614
	}
615
	
616
	protected static void resetHttpClient() {
617
		httpClient = null;
618
	}
619
	
620
	/**
621
	 * Create a unique docid for testing insert and update. Does not
622
	 * include the 'revision' part of the id.
623
	 * 
624
	 * @return a String docid based on the current date and time
625
	 */
626
	protected String generateDocumentId() {
627
		try {
628
			Thread.sleep(1010);
629
		} catch (InterruptedException ie) {
630
			debug("Could not sleep: " + ie.getMessage());
631
		}
632

    
633
		return DocumentUtil.generateDocumentId(prefix, 0);
634
	}
635
	
636
	/**
637
	 * Insert a document into metacat. The expected result is passed as result
638
	 */
639
	protected String insertDocumentId(String docid, String docText, boolean result,
640
			boolean expectKarmaException) {
641
		debug("insertDocumentId() - docid=" + docid + " expectedResult=" + result
642
				+ " expectKarmaException=" + expectKarmaException);
643
		String response = null;
644
		try {
645
			response = m.insert(docid, new StringReader(docText), null);
646
			if (result) {
647
				assertTrue(response, (response.indexOf("<success>") != -1));
648
				assertTrue(response, response.indexOf(docid) != -1);
649
			} else {
650
				assertTrue(response, (response.indexOf("<success>") == -1));
651
			}
652
			debug("insertDocid():  response=" + response);
653
		} catch (MetacatInaccessibleException mie) {
654
			fail("Metacat Inaccessible:\n" + mie.getMessage());
655
		} catch (InsufficientKarmaException ike) {
656
			if (!expectKarmaException) {
657
				fail("Insufficient karma:\n" + ike.getMessage());
658
			}
659
		} catch (MetacatException me) {
660
			fail("Metacat Error:\n" + me.getMessage());
661
		} catch (Exception e) {
662
			fail("General exception:\n" + e.getMessage());
663
		}
664
		return response;
665
	}
666

    
667
	/**
668
	 * Insert a document into metacat. The expected result is passed as result
669
	 */
670

    
671
	protected String uploadDocumentId(String docid, String filePath, boolean result,
672
			boolean expectedKarmaException) {
673
		debug("uploadDocumentId() - docid=" + docid + " filePath=" + filePath
674
				+ " expectedResult=" + result + " expectedKarmaException="
675
				+ expectedKarmaException);
676
		String response = null;
677
		try {
678
			response = m.upload(docid, new File(filePath));
679
			if (result) {
680
				assertTrue(response, (response.indexOf("<success>") != -1));
681
				assertTrue(response, response.indexOf(docid) != -1);
682
			} else {
683
				assertTrue(response, (response.indexOf("<success>") == -1));
684
			}
685
			debug("uploadDocid():  response=" + response);
686
		} catch (MetacatInaccessibleException mie) {
687
			fail("Metacat Inaccessible:\n" + mie.getMessage());
688
		} catch (InsufficientKarmaException ike) {
689
			if (!expectedKarmaException) {
690
				fail("Insufficient karma:\n" + ike.getMessage());
691
			}
692
		} catch (MetacatException me) {
693
			if (result) {
694
				fail("Metacat Error:\n" + me.getMessage());
695
			} else {
696
				debug("Metacat Error:\n" + me.getMessage());
697
			}
698
		} catch (Exception e) {
699
			fail("General exception:\n" + e.getMessage());
700
		}
701
		return response;
702
	}
703

    
704
	/**
705
	 * Update a document in metacat. The expected result is passed as result
706
	 */
707
	protected String updateDocumentId(String docid, String docText, boolean result,
708
			boolean expectedKarmaFailure) {
709
		debug("updateDocumentId() - docid=" + docid + " expectedResult=" + result
710
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
711
		String response = null;
712
		try {
713
			response = m.update(docid, new StringReader(testdocument), null);
714
			debug("updateDocumentId() - response=" + response);
715
			
716
			if (result) {
717
				assertTrue(response, (response.indexOf("<success>") != -1));
718
				assertTrue(response, response.indexOf(docid) != -1);
719
			} else {
720
				assertTrue(response, (response.indexOf("<success>") == -1));
721
			}			
722
		} catch (MetacatInaccessibleException mie) {
723
			fail("Metacat Inaccessible:\n" + mie.getMessage());
724
		} catch (InsufficientKarmaException ike) {
725
			if (!expectedKarmaFailure) {
726
				fail("Insufficient karma:\n" + ike.getMessage());
727
			}
728
		} catch (MetacatException me) {
729
			if (result) {
730
				fail("Metacat Error:\n" + me.getMessage());
731
			} else {
732
				debug("Metacat Error:\n" + me.getMessage());
733
			}
734
		} catch (Exception e) {
735
			fail("General exception:\n" + e.getMessage());
736
		}
737

    
738
		return response;
739
	}
740

    
741
	/**
742
	 * Delete a document into metacat. The expected result is passed as result
743
	 */
744
	protected void deleteDocumentId(String docid, boolean result, boolean expectedKarmaFailure) {
745
		debug("deleteDocumentId() - docid=" + docid + " expectedResult=" + result
746
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
747
		try {
748
			Thread.sleep(5000);
749
			String response = m.delete(docid);
750
			debug("deleteDocumentId() -  response=" + response);
751
			
752
			if (result) {
753
				assertTrue(response, response.indexOf("<success>") != -1);
754
			} else {
755
				assertTrue(response, response.indexOf("<success>") == -1);
756
			}
757
		} catch (MetacatInaccessibleException mie) {
758
			fail("Metacat Inaccessible:\n" + mie.getMessage());
759
		} catch (InsufficientKarmaException ike) {
760
			if (!expectedKarmaFailure) {
761
				fail("Insufficient karma:\n" + ike.getMessage());
762
			}
763
		} catch (MetacatException me) {
764
			if (result) {
765
				fail("Metacat Error:\n" + me.getMessage());
766
			} else {
767
				debug("Metacat Error:\n" + me.getMessage());
768
			}
769
		} catch (Exception e) {
770
			fail("General exception:\n" + e.getMessage());
771
		}
772
	}
773
	
774
	/**
775
	 * Read a document from metacat and check if it is equal to a given string.
776
	 * The expected result is passed as result
777
	 */
778
	protected void readDocumentIdWhichEqualsDoc(String docid, String testDoc, boolean result,
779
			boolean expectedKarmaFailure) {
780
		debug("readDocumentIdWhichEqualsDoc() - docid=" + docid + " expectedResult=" + result
781
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
782
		try {
783
			Reader r = new InputStreamReader(m.read(docid));
784
			String doc = IOUtil.getAsString(r, true);
785
			debug("readDocumentIdWhichEqualsDoc() -  doc=" + doc);
786
			
787
			if (result) {
788

    
789
				if (!testDoc.equals(doc)) {
790
					System.out.println("doc ***********************");
791
					System.out.println(doc);
792
					System.out.println("end doc ***********************");
793
					System.out.println("testDoc ***********************");
794
					System.out.println(testDoc);
795
					System.out.println("end testDoc ***********************");
796
				}
797

    
798
				assertTrue(testDoc.equals(doc));
799
			} else {
800
				assertTrue(doc.indexOf("<error>") != -1);
801
			}
802
		} catch (MetacatInaccessibleException mie) {
803
			fail("Metacat Inaccessible:\n" + mie.getMessage());
804
		} catch (InsufficientKarmaException ike) {
805
			if (!expectedKarmaFailure) {
806
				fail("Insufficient karma:\n" + ike.getMessage());
807
			}
808
		} catch (MetacatException me) {
809
			fail("Metacat Error:\n" + me.getMessage());
810
		} catch (Exception e) {
811
			fail("General exception:\n" + e.getMessage());
812
		}
813

    
814
	}
815

    
816
}
    (1-1/1)