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: tao $'
8
 *     '$Date: 2014-01-16 17:00:47 -0800 (Thu, 16 Jan 2014) $'
9
 * '$Revision: 8506 $'
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.authentication.AuthFile;
49
import edu.ucsb.nceas.metacat.client.InsufficientKarmaException;
50
import edu.ucsb.nceas.metacat.client.Metacat;
51
import edu.ucsb.nceas.metacat.client.MetacatException;
52
import edu.ucsb.nceas.metacat.client.MetacatFactory;
53
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
54
import edu.ucsb.nceas.metacat.database.DBConnection;
55
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
56
import edu.ucsb.nceas.metacat.properties.PropertyService;
57
import edu.ucsb.nceas.metacat.shared.ServiceException;
58
import edu.ucsb.nceas.metacat.util.DocumentUtil;
59
import edu.ucsb.nceas.metacat.util.RequestUtil;
60
import edu.ucsb.nceas.utilities.IOUtil;
61
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
62
import edu.ucsb.nceas.utilities.SortedProperties;
63

    
64
/**
65
 * A base JUnit class for Metacat tests
66
 */
67
public class MCTestCase
68
    extends TestCase {
69
	
70
    private static boolean printDebug = false;
71
    
72
	protected static String EML2_0_0 = "EML2_0_0";
73
	protected static String EML2_0_1 = "EML2_0_1";
74
	protected static String EML2_1_0 = "EML2_1_0";
75
	protected static String EML2_1_1 = "EML2_1_1";
76
	protected static final String AUTHFILECLASSNAME = "edu.ucsb.nceas.metacat.authentication.AuthFile";
77

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

    
94
	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
	private static String lteruser;
100
	private static String lterpassword;
101
	protected static String referraluser;
102
	protected static String referralpassword;
103
	
104
	protected static String metacatContextDir;
105
	
106
	static {
107
		try {
108
			SortedProperties testProperties = 
109
				new SortedProperties("build/tests/test.properties");
110
			testProperties.load();
111
			metacatContextDir = testProperties.getProperty("metacat.contextDir");
112
			PropertyService.getInstance(metacatContextDir + "/WEB-INF");
113
//			PropertyService.getInstance();
114
		    String printDebugString = PropertyService.getProperty("test.printdebug");
115
		    printDebug = Boolean.parseBoolean(printDebugString);
116

    
117
		    metacatUrl = PropertyService.getProperty("test.metacatUrl");
118
			username = PropertyService.getProperty("test.mcUser");
119
			password = PropertyService.getProperty("test.mcPassword");
120
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
121
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
122
			lteruser = PropertyService.getProperty("test.lterUser");
123
			lterpassword = PropertyService.getProperty("test.lterPassword");
124
			referraluser = PropertyService.getProperty("test.referralUser");
125
            referralpassword = PropertyService.getProperty("test.referralPassword");
126
			String authenClass = PropertyService.getProperty("auth.class");
127
			if(authenClass != null && authenClass.equals(AUTHFILECLASSNAME)) {
128
			    //add those test users to the authentication file
129
			    AuthFile authFile = new AuthFile();
130
			    String[] groups = null;
131
			    try {
132
			        authFile.addUser(username, groups, password, null, null, null, null, null);
133
			    } catch (Exception e) {
134
			        System.out.println("Couldn't add the user "+username+" to the password file since "+e.getMessage());
135
			    }
136
			    
137
			    try {
138
                    authFile.addUser(anotheruser, groups, anotherpassword, null, null, null, null, null);
139
                } catch (Exception e) {
140
                    System.out.println("Couldn't add the user "+anotheruser+" to the password file since "+e.getMessage());
141
                }
142
			    try {
143
                    authFile.addUser(lteruser, groups, lterpassword, null, null, null, null, null);
144
                } catch (Exception e) {
145
                    System.out.println("Couldn't add the user "+lteruser+" to the password file since "+e.getMessage());
146
                }
147
			    try {
148
                    authFile.addUser(referraluser, groups, referralpassword, null, null, null, null, null);
149
                } catch (Exception e) {
150
                    System.out.println("Couldn't add the user "+referraluser+" to the password file since "+e.getMessage());
151
                }
152
			}
153
		} catch (IOException ioe) {
154
			System.err.println("Could not read property file in static block: " 
155
					+ ioe.getMessage());
156
		} catch (PropertyNotFoundException pnfe) {
157
			System.err.println("Could not get property in static block: " 
158
					+ pnfe.getMessage());
159
		} catch (ServiceException se) {
160
			System.err.println("Could not get PropertyService instance in static block: " 
161
					+ se.getMessage());
162
		}
163
	}
164
	
165
	// header blocks
166
	protected String testEml_200_Header = "<?xml version=\"1.0\"?><eml:eml"
167
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\""
168
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
169
		+ " packageId=\"eml.1.1\" system=\"knb\""
170
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\""
171
		+ " scope=\"system\">";
172
	
173
	protected String testEml_201_Header = "<?xml version=\"1.0\"?><eml:eml"
174
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\""
175
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
176
		+ " packageId=\"eml.1.1\" system=\"knb\""
177
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\""
178
		+ " scope=\"system\">";
179
	
180
	protected String testEml_210_Header = "<?xml version=\"1.0\"?><eml:eml"
181
			+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.0\""
182
			+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
183
			+ " packageId=\"eml.1.1\" system=\"knb\""
184
			+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.0 eml.xsd\""
185
			+ " scope=\"system\">";
186
	
187
	protected String testEml_211_Header = "<?xml version=\"1.0\"?><eml:eml"
188
		+ " xmlns:eml=\"eml://ecoinformatics.org/eml-2.1.1\""
189
		+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
190
		+ " packageId=\"eml.1.1\" system=\"knb\""
191
		+ " xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.1.1 eml.xsd\""
192
		+ " scope=\"system\">";
193

    
194
	protected String testEmlCreatorBlock = "<creator scope=\"document\">                                       "
195
			+ " <individualName>                                                  "
196
			+ "    <surName>Smith</surName>                                       "
197
			+ " </individualName>                                                 "
198
			+ "</creator>                                                         ";
199

    
200
	protected String testEmlContactBlock = "<contact scope=\"document\">                                       "
201
			+ " <individualName>                                                  "
202
			+ "    <surName>Jackson</surName>                                     "
203
			+ " </individualName>                                                 "
204
			+ "</contact>                                                         ";
205

    
206
	protected String testEmlInlineBlock1 = "<inline>                                                           "
207
			+ "  <admin>                                                          "
208
			+ "    <contact>                                                      "
209
			+ "      <name>Operator</name>                                        "
210
			+ "      <institution>PSI</institution>                               "
211
			+ "    </contact>                                                     "
212
			+ "  </admin>                                                         "
213
			+ "</inline>                                                          ";
214

    
215
	protected String testEmlInlineBlock2 = "<inline>                                                           "
216
			+ "  <instrument>                                                     "
217
			+ "    <instName>LCQ</instName>                                       "
218
			+ "    <source type=\"ESI\"></source>                                 "
219
			+ "    <detector type=\"EM\"></detector>                              "
220
			+ "  </instrument>                                                    "
221
			+ "</inline>                                                          ";
222

    
223
    
224
    /**
225
     * Returns an xml squery that searches for the doc id in the
226
     * title of documents. This function is for eml-2.0.1+ only. For 
227
     * other eml versions, this function might have to modified.
228
     */
229
    protected String getTestEmlQuery(String titlePart, String emlVersion) {
230

    
231
    	String docType;
232
    	if (emlVersion.equals(EML2_0_1)) {
233
    		docType = "eml://ecoinformatics.org/eml-2.0.1";
234
    	} else if (emlVersion.equals(EML2_1_0)) {
235
    		docType = "eml://ecoinformatics.org/eml-2.1.0";
236
    	} else { //if (emlVersion.equals(EML2_1_1)) {
237
    		docType = "eml://ecoinformatics.org/eml-2.1.1";
238
    	}
239
    	
240
        String sQuery = "";
241
        sQuery = 
242
        	"<pathquery version=\"1.0\">" +
243
        		"<meta_file_id>unspecified</meta_file_id>" +
244
        		"<querytitle>unspecified</querytitle>" + 
245
        		"<returnfield>dataset/title</returnfield>" +
246
        		"<returndoctype>" + docType + "</returndoctype>" +
247
        		"<querygroup operator=\"UNION\">" +
248
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
249
        				"<value>" + titlePart + "</value>" +
250
        				"<pathexpr>dataset/title</pathexpr>" +
251
        			"</queryterm>" +
252
        		"</querygroup>" +
253
        	"</pathquery>";
254

    
255
        return sQuery;
256
    }
257
	
258
	/**
259
     * Query a document by looking for a part of the title in the title element.
260
     * Then check if the testTitle exists in the doc.
261
     * @param titlePart the part of the title of the doc to look for
262
     * @param testTitle the title containing special characters
263
     * @param result are we expecting SUCCESS or FAILURE
264
     * @param expextedKarmaFailure
265
     */
266
    protected void queryDocWhichHasTitle(String titlePart, String testTitle,
267
                                         String emlVersion, boolean result) {
268
        try {
269
            String sQuery = getTestEmlQuery(titlePart, emlVersion);
270
        	Reader queryReader = new StringReader(sQuery);
271
            Reader resultReader = m.query(queryReader);
272
            String queryResult = IOUtil.getAsString(resultReader, true);
273
            if (result) {
274
                if (!queryResult.contains(testTitle)) {
275
                    debug("queryResult: " + queryResult);
276
                    debug("does not contain title: " + testTitle);
277
                }
278

    
279
                assertTrue(queryResult.contains(testTitle));
280
            }
281
            else {
282
                assertTrue(queryResult.indexOf("<error>") != -1);
283
            }
284
        }
285
        catch (MetacatInaccessibleException mie) {
286
            fail("Metacat Inaccessible:\n" + mie.getMessage());
287
        }
288
        catch (Exception e) {
289
            fail("General exception:\n" + e.getMessage());
290
        }
291

    
292
    }
293
	
294
	/*
295
	 * Retrus an access block base on params passed and the defaul perm order -
296
	 * allow first
297
	 */
298
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
299
			boolean write, boolean changePermission, boolean all) {
300
		return getAccessBlock(principal, grantAccess, read, write, changePermission, all,
301
				ALLOWFIRST);
302
	}
303

    
304
	/**
305
	 * This function returns an access block based on the params passed
306
	 */
307
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
308
			boolean write, boolean changePermission, boolean all, String permOrder) {
309
		String accessBlock = "<access "
310
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
311
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
312

    
313
		accessBlock += generateOneAccessRule(principal, grantAccess, read, write,
314
				changePermission, all);
315
		accessBlock += "</access>";
316

    
317
		return accessBlock;
318

    
319
	}
320

    
321
	/*
322
	 * Gets eml access block base on given acccess rules and perm order
323
	 */
324
	protected String getAccessBlock(Vector<String> accessRules, String permOrder) {
325
		String accessBlock = "<access "
326
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
327
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
328
		// adding rules
329
		if (accessRules != null && !accessRules.isEmpty()) {
330
			for (int i = 0; i < accessRules.size(); i++) {
331
				String rule = (String) accessRules.elementAt(i);
332
				accessBlock += rule;
333

    
334
			}
335
		}
336
		accessBlock += "</access>";
337
		return accessBlock;
338
	}
339

    
340
	/*
341
	 * Generates a access rule for given parameter. Note this xml portion
342
	 * doesn't include <access></access>
343
	 */
344
	protected String generateOneAccessRule(String principal, boolean grantAccess,
345
			boolean read, boolean write, boolean changePermission, boolean all) {
346
		String accessBlock = "";
347

    
348
		if (grantAccess) {
349
			accessBlock = "<allow>";
350
		} else {
351
			accessBlock = "<deny>";
352
		}
353

    
354
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
355

    
356
		if (all) {
357
			accessBlock += "<permission>all</permission>";
358
		} else {
359
			if (read) {
360
				accessBlock += "<permission>read</permission>";
361
			}
362
			if (write) {
363
				accessBlock += "<permission>write</permission>";
364
			}
365
			if (changePermission) {
366
				accessBlock += "<permission>changePermission</permission>";
367
			}
368
		}
369

    
370
		if (grantAccess) {
371
			accessBlock += "</allow>";
372
		} else {
373
			accessBlock += "</deny>";
374
		}
375
		return accessBlock;
376

    
377
	}
378
	
379
    /**
380
     * This function returns a valid eml document with public read access
381
     */
382
    protected String getTestEmlDoc(String title, String emlVersion) {
383

    
384
        String testDocument = "";
385

    
386
        String header;
387
		if (emlVersion == EML2_0_1) {
388
			header = testEml_201_Header;
389
		} else if (emlVersion == EML2_1_0) {
390
			header = testEml_210_Header;
391
		} else { // if (emlVersion == EML2_1_1) {
392
			header = testEml_211_Header;
393
		}
394
        
395
        testDocument += header;
396
        
397
        // if this is an EML 2.1.0 or later document, the document level access is
398
        // before the dataset element.
399
        if (emlVersion == EML2_1_0 || emlVersion == EML2_1_1) {
400
        	testDocument += getAccessBlock("public", true, true, false, false, false);
401
        }
402
        testDocument += "<dataset scope=\"document\"><title>" + title + "</title>"
403
				+ testEmlCreatorBlock;
404

    
405
        testDocument += testEmlContactBlock;
406
        
407
        // if this is an EML 2.0.1 or earlier document, the document level access is
408
        // inside the dataset element.
409
        if (emlVersion != EML2_1_0 && emlVersion != EML2_1_1) {
410
        	testDocument += getAccessBlock("public", true, true, false, false, false);
411
        }
412
        testDocument += "</dataset>";
413
        testDocument += "</eml:eml>";
414

    
415
        return testDocument;
416
    }
417

    
418
	/**
419
	 * This function returns a valid eml document with no access rules 
420
	 */
421
	protected String getTestEmlDoc(String title, String emlVersion, String inlineData1,
422
			String inlineData2, String onlineUrl1, String onlineUrl2,
423
			String docAccessBlock, String inlineAccessBlock1, String inlineAccessBlock2,
424
			String onlineAccessBlock1, String onlineAccessBlock2) {
425

    
426
		debug("getTestEmlDoc(): title=" + title + " inlineData1=" + inlineData1
427
				+ " inlineData2=" + inlineData2 + " onlineUrl1=" + onlineUrl1
428
				+ " onlineUrl2=" + onlineUrl2 + " docAccessBlock=" + docAccessBlock
429
				+ " inlineAccessBlock1=" + inlineAccessBlock1 + " inlineAccessBlock2="
430
				+ inlineAccessBlock2 + " onlineAccessBlock1=" + onlineAccessBlock1
431
				+ " onlineAccessBlock2=" + onlineAccessBlock2);
432
		String testDocument = "";
433
		String header;
434
		if (emlVersion == EML2_0_0) {
435
			header = testEml_200_Header;
436
		} else if (emlVersion == EML2_0_1) {
437
			header = testEml_201_Header;
438
		} else if (emlVersion == EML2_1_0) {
439
			header = testEml_210_Header;
440
		} else { // if (emlVersion == EML2_1_1) {
441
			header = testEml_211_Header;
442
		}
443
		testDocument += header;
444
		
445
		// if this is a 2.1.0+ document, the document level access block sits
446
		// at the same level and before the dataset element.
447
		if (docAccessBlock != null && (emlVersion.equals(EML2_1_0) || emlVersion.equals(EML2_1_1))) {
448
			testDocument += docAccessBlock;
449
		}
450
		
451
		testDocument += "<dataset scope=\"document\"><title>"
452
				+ title + "</title>" + testEmlCreatorBlock;
453

    
454
		if (inlineData1 != null) {
455
			testDocument = testDocument
456
					+ "<distribution scope=\"document\" id=\"inlineEntity1\">"
457
					+ inlineData1 + "</distribution>";
458
		}
459
		if (inlineData2 != null) {
460
			testDocument = testDocument
461
					+ "<distribution scope=\"document\" id=\"inlineEntity2\">"
462
					+ inlineData2 + "</distribution>";
463
		}
464
		if (onlineUrl1 != null) {
465
			testDocument = testDocument
466
					+ "<distribution scope=\"document\" id=\"onlineEntity1\">"
467
					+ "<online><url function=\"download\">" + onlineUrl1
468
					+ "</url></online></distribution>";
469
		}
470
		if (onlineUrl2 != null) {
471
			testDocument = testDocument
472
					+ "<distribution scope=\"document\" id=\"onlineEntity2\">"
473
					+ "<online><url function=\"download\">" + onlineUrl2
474
					+ "</url></online></distribution>";
475
		}
476
		testDocument += testEmlContactBlock;
477

    
478
		// if this is a 2.0.X document, the document level access block sits
479
		// inside the dataset element.
480
		if (docAccessBlock != null && 
481
				(emlVersion.equals(EML2_0_0) || emlVersion.equals(EML2_0_1))) {
482
			testDocument += docAccessBlock;
483
		}
484

    
485
		testDocument += "</dataset>";
486

    
487
		if (inlineAccessBlock1 != null) {
488
			testDocument += "<additionalMetadata>";
489
			testDocument += "<describes>inlineEntity1</describes>";
490
			testDocument += inlineAccessBlock1;
491
			testDocument += "</additionalMetadata>";
492
		}
493

    
494
		if (inlineAccessBlock2 != null) {
495
			testDocument += "<additionalMetadata>";
496
			testDocument += "<describes>inlineEntity2</describes>";
497
			testDocument += inlineAccessBlock2;
498
			testDocument += "</additionalMetadata>";
499
		}
500

    
501
		if (onlineAccessBlock1 != null) {
502
			testDocument += "<additionalMetadata>";
503
			testDocument += "<describes>onlineEntity1</describes>";
504
			testDocument += onlineAccessBlock1;
505
			testDocument += "</additionalMetadata>";
506
		}
507

    
508
		if (onlineAccessBlock2 != null) {
509
			testDocument += "<additionalMetadata>";
510
			testDocument += "<describes>onlineEntity2</describes>";
511
			testDocument += onlineAccessBlock2;
512
			testDocument += "</additionalMetadata>";
513
		}
514

    
515
		testDocument += "</eml:eml>";
516

    
517
		// System.out.println("Returning following document" + testDocument);
518
		return testDocument;
519
	}
520
	
521
	/**
522
	 * 
523
	 */
524
	protected String getTestDocFromFile(String filePath) throws IOException{
525
		StringBuffer output = new StringBuffer();
526
		
527
		FileReader fileReader = new FileReader(new File(filePath));
528
		BufferedReader bufferedReader = new BufferedReader(fileReader);
529
		String readLine = null;
530
		
531
		while ((readLine = bufferedReader.readLine()) != null) {
532
			output.append(readLine);
533
		}
534
		
535
		return output.toString();
536
	}
537

    
538
	
539
    /**
540
     * Constructor to build the test
541
     */
542
    public MCTestCase() {
543
        super();
544
    }
545
	
546
    /**
547
     * Constructor to build the test
548
     *
549
     * @param name the name of the test method
550
     */
551
    public MCTestCase(String name) {
552
        super(name);
553
    }
554
    
555
	/**
556
	 * Establish a testing framework by initializing appropriate objects
557
	 */
558
	protected void setUp() throws Exception {
559
		try {
560
			if (metacatConnectionNeeded) {
561
				debug("setUp() - Testing Metacat Url: " + metacatUrl);
562
				m = MetacatFactory.createMetacatConnection(metacatUrl);
563
			}
564
		} catch (MetacatInaccessibleException mie) {
565
			System.err.println("Metacat is: " + metacatUrl);
566
			fail("Metacat connection failed." + mie.getMessage());
567
		}
568
	}
569
    
570
    protected static void debug(String debugMessage) {
571
    	if (printDebug) {
572
    		System.err.println(debugMessage);
573
    	}
574
    }
575
    
576
	protected static Vector<Hashtable<String, Object>> dbSelect(String sqlStatement,
577
			String methodName) throws SQLException {
578
		Vector<Hashtable<String, Object>> resultVector = new Vector<Hashtable<String, Object>>();
579

    
580
		DBConnectionPool connPool = DBConnectionPool.getInstance();
581
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
582
		int serialNumber = dbconn.getCheckOutSerialNumber();
583

    
584
		PreparedStatement pstmt = null;
585

    
586
		debug("Selecting from db: " + sqlStatement);
587
		pstmt = dbconn.prepareStatement(sqlStatement);
588
		pstmt.execute();
589

    
590
		ResultSet resultSet = pstmt.getResultSet();
591
		ResultSetMetaData rsMetaData = resultSet.getMetaData();
592
		int numColumns = rsMetaData.getColumnCount();
593
		debug("Number of data columns: " + numColumns);
594
		while (resultSet.next()) {
595
			Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
596
			for (int i = 1; i <= numColumns; i++) {
597
				if (resultSet.getObject(i) != null) {
598
					hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i));
599
				}
600
			}
601
			debug("adding data row to result vector");
602
			resultVector.add(hashTable);
603
		}
604

    
605
		resultSet.close();
606
		pstmt.close();
607
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
608

    
609
		return resultVector;
610
	}
611
	
612
	protected static void dbQuery(String sqlStatement, String methodName)
613
			throws SQLException {
614

    
615
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
616
		int serialNumber = dbconn.getCheckOutSerialNumber();
617

    
618
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
619
		debug("Executing against db: " + sqlStatement);
620
		statement.executeQuery();
621

    
622
		statement.close();
623
		
624
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
625
	}
626
	
627
	protected static void dbUpdate(String sqlStatement, String methodName)
628
			throws SQLException {
629

    
630
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
631
		int serialNumber = dbconn.getCheckOutSerialNumber();
632

    
633
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
634
		debug("Executing against db: " + sqlStatement);
635
		statement.executeUpdate();
636
		statement.close();
637

    
638
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
639
	}
640
	
641
	protected static void httpPost(String url, HashMap<String,String> paramMap) throws Exception {
642
		debug("Posting to: " + url);
643
		if (httpClient == null) {
644
			httpClient = new DefaultHttpClient();
645
		}
646
		String postResponse = RequestUtil.post(httpClient, url, paramMap);
647
		debug("Post response: " + postResponse);
648
		if (postResponse.contains("<error>")) {
649
			fail("Error posting to metacat: " + postResponse);
650
		}
651
	}
652
	
653
	protected static void resetHttpClient() {
654
		httpClient = null;
655
	}
656
	
657
	/**
658
	 * Create a unique docid for testing insert and update. Does not
659
	 * include the 'revision' part of the id.
660
	 * 
661
	 * @return a String docid based on the current date and time
662
	 */
663
	protected String generateDocumentId() {
664
		try {
665
			Thread.sleep(1010);
666
		} catch (InterruptedException ie) {
667
			debug("Could not sleep: " + ie.getMessage());
668
		}
669

    
670
		return DocumentUtil.generateDocumentId(prefix, 0);
671
	}
672
	
673
	/**
674
	 * Insert a document into metacat. The expected result is passed as result
675
	 */
676
	protected String insertDocumentId(String docid, String docText, boolean result,
677
			boolean expectKarmaException) {
678
		debug("insertDocumentId() - docid=" + docid + " expectedResult=" + result
679
				+ " expectKarmaException=" + expectKarmaException);
680
		String response = null;
681
		try {
682
			response = m.insert(docid, new StringReader(docText), null);
683
			if (result) {
684
				assertTrue(response, (response.indexOf("<success>") != -1));
685
				assertTrue(response, response.indexOf(docid) != -1);
686
			} else {
687
				assertTrue(response, (response.indexOf("<success>") == -1));
688
			}
689
			debug("insertDocid():  response=" + response);
690
		} catch (MetacatInaccessibleException mie) {
691
			fail("Metacat Inaccessible:\n" + mie.getMessage());
692
		} catch (InsufficientKarmaException ike) {
693
			if (!expectKarmaException) {
694
				fail("Insufficient karma:\n" + ike.getMessage());
695
			}
696
		} catch (MetacatException me) {
697
			fail("Metacat Error:\n" + me.getMessage());
698
		} catch (Exception e) {
699
			fail("General exception:\n" + e.getMessage());
700
		}
701
		return response;
702
	}
703

    
704
	/**
705
	 * Insert a document into metacat. The expected result is passed as result
706
	 */
707

    
708
	protected String uploadDocumentId(String docid, String filePath, boolean result,
709
			boolean expectedKarmaException) {
710
		debug("uploadDocumentId() - docid=" + docid + " filePath=" + filePath
711
				+ " expectedResult=" + result + " expectedKarmaException="
712
				+ expectedKarmaException);
713
		String response = null;
714
		try {
715
			response = m.upload(docid, new File(filePath));
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
			debug("uploadDocid():  response=" + response);
723
		} catch (MetacatInaccessibleException mie) {
724
			fail("Metacat Inaccessible:\n" + mie.getMessage());
725
		} catch (InsufficientKarmaException ike) {
726
			if (!expectedKarmaException) {
727
				fail("Insufficient karma:\n" + ike.getMessage());
728
			}
729
		} catch (MetacatException me) {
730
			if (result) {
731
				fail("Metacat Error:\n" + me.getMessage());
732
			} else {
733
				debug("Metacat Error:\n" + me.getMessage());
734
			}
735
		} catch (Exception e) {
736
			fail("General exception:\n" + e.getMessage());
737
		}
738
		return response;
739
	}
740

    
741
	/**
742
	 * Update a document in metacat. The expected result is passed as result
743
	 */
744
	protected String updateDocumentId(String docid, String docText, boolean result,
745
			boolean expectedKarmaFailure) {
746
		debug("updateDocumentId() - docid=" + docid + " expectedResult=" + result
747
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
748
		String response = null;
749
		try {
750
			response = m.update(docid, new StringReader(testdocument), null);
751
			debug("updateDocumentId() - response=" + response);
752
			
753
			if (result) {
754
				assertTrue(response, (response.indexOf("<success>") != -1));
755
				assertTrue(response, response.indexOf(docid) != -1);
756
			} else {
757
				assertTrue(response, (response.indexOf("<success>") == -1));
758
			}			
759
		} catch (MetacatInaccessibleException mie) {
760
			fail("Metacat Inaccessible:\n" + mie.getMessage());
761
		} catch (InsufficientKarmaException ike) {
762
			if (!expectedKarmaFailure) {
763
				fail("Insufficient karma:\n" + ike.getMessage());
764
			}
765
		} catch (MetacatException me) {
766
			if (result) {
767
				fail("Metacat Error:\n" + me.getMessage());
768
			} else {
769
				debug("Metacat Error:\n" + me.getMessage());
770
			}
771
		} catch (Exception e) {
772
			fail("General exception:\n" + e.getMessage());
773
		}
774

    
775
		return response;
776
	}
777

    
778
	/**
779
	 * Delete a document into metacat. The expected result is passed as result
780
	 */
781
	protected void deleteDocumentId(String docid, boolean result, boolean expectedKarmaFailure) {
782
		debug("deleteDocumentId() - docid=" + docid + " expectedResult=" + result
783
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
784
		try {
785
			Thread.sleep(5000);
786
			String response = m.delete(docid);
787
			debug("deleteDocumentId() -  response=" + response);
788
			
789
			if (result) {
790
				assertTrue(response, response.indexOf("<success>") != -1);
791
			} else {
792
				assertTrue(response, response.indexOf("<success>") == -1);
793
			}
794
		} catch (MetacatInaccessibleException mie) {
795
			fail("Metacat Inaccessible:\n" + mie.getMessage());
796
		} catch (InsufficientKarmaException ike) {
797
			if (!expectedKarmaFailure) {
798
				fail("Insufficient karma:\n" + ike.getMessage());
799
			}
800
		} catch (MetacatException me) {
801
			if (result) {
802
				fail("Metacat Error:\n" + me.getMessage());
803
			} else {
804
				debug("Metacat Error:\n" + me.getMessage());
805
			}
806
		} catch (Exception e) {
807
			fail("General exception:\n" + e.getMessage());
808
		}
809
	}
810
	
811
	/**
812
	 * Read a document from metacat and check if it is equal to a given string.
813
	 * The expected result is passed as result
814
	 */
815
	protected void readDocumentIdWhichEqualsDoc(String docid, String testDoc, boolean result,
816
			boolean expectedKarmaFailure) {
817
		debug("readDocumentIdWhichEqualsDoc() - docid=" + docid + " expectedResult=" + result
818
				+ " expectedKarmaFailure=" + expectedKarmaFailure);
819
		try {
820
			Reader r = new InputStreamReader(m.read(docid));
821
			String doc = IOUtil.getAsString(r, true);
822
			debug("readDocumentIdWhichEqualsDoc() -  doc=" + doc);
823
			
824
			if (result) {
825

    
826
				if (!testDoc.equals(doc)) {
827
					System.out.println("doc ***********************");
828
					System.out.println(doc);
829
					System.out.println("end doc ***********************");
830
					System.out.println("testDoc ***********************");
831
					System.out.println(testDoc);
832
					System.out.println("end testDoc ***********************");
833
				}
834

    
835
				assertTrue(testDoc.equals(doc));
836
			} else {
837
				assertTrue(doc.indexOf("<error>") != -1);
838
			}
839
		} catch (MetacatInaccessibleException mie) {
840
			fail("Metacat Inaccessible:\n" + mie.getMessage());
841
		} catch (InsufficientKarmaException ike) {
842
			if (!expectedKarmaFailure) {
843
				fail("Insufficient karma:\n" + ike.getMessage());
844
			}
845
		} catch (MetacatException me) {
846
			fail("Metacat Error:\n" + me.getMessage());
847
		} catch (Exception e) {
848
			fail("General exception:\n" + e.getMessage());
849
		}
850

    
851
	}
852

    
853
}
    (1-1/1)