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-17 11:58:31 -0800 (Fri, 17 Jan 2014) $'
9
 * '$Revision: 8507 $'
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
	private static final String KNBUSERGOURP = "cn=knb-usr,o=NCEAS,dc=ecoinformatics,dc=org";
78

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

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

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

    
203
	protected String testEmlCreatorBlock = "<creator scope=\"document\">                                       "
204
			+ " <individualName>                                                  "
205
			+ "    <surName>Smith</surName>                                       "
206
			+ " </individualName>                                                 "
207
			+ "</creator>                                                         ";
208

    
209
	protected String testEmlContactBlock = "<contact scope=\"document\">                                       "
210
			+ " <individualName>                                                  "
211
			+ "    <surName>Jackson</surName>                                     "
212
			+ " </individualName>                                                 "
213
			+ "</contact>                                                         ";
214

    
215
	protected String testEmlInlineBlock1 = "<inline>                                                           "
216
			+ "  <admin>                                                          "
217
			+ "    <contact>                                                      "
218
			+ "      <name>Operator</name>                                        "
219
			+ "      <institution>PSI</institution>                               "
220
			+ "    </contact>                                                     "
221
			+ "  </admin>                                                         "
222
			+ "</inline>                                                          ";
223

    
224
	protected String testEmlInlineBlock2 = "<inline>                                                           "
225
			+ "  <instrument>                                                     "
226
			+ "    <instName>LCQ</instName>                                       "
227
			+ "    <source type=\"ESI\"></source>                                 "
228
			+ "    <detector type=\"EM\"></detector>                              "
229
			+ "  </instrument>                                                    "
230
			+ "</inline>                                                          ";
231

    
232
    
233
    /**
234
     * Returns an xml squery that searches for the doc id in the
235
     * title of documents. This function is for eml-2.0.1+ only. For 
236
     * other eml versions, this function might have to modified.
237
     */
238
    protected String getTestEmlQuery(String titlePart, String emlVersion) {
239

    
240
    	String docType;
241
    	if (emlVersion.equals(EML2_0_1)) {
242
    		docType = "eml://ecoinformatics.org/eml-2.0.1";
243
    	} else if (emlVersion.equals(EML2_1_0)) {
244
    		docType = "eml://ecoinformatics.org/eml-2.1.0";
245
    	} else { //if (emlVersion.equals(EML2_1_1)) {
246
    		docType = "eml://ecoinformatics.org/eml-2.1.1";
247
    	}
248
    	
249
        String sQuery = "";
250
        sQuery = 
251
        	"<pathquery version=\"1.0\">" +
252
        		"<meta_file_id>unspecified</meta_file_id>" +
253
        		"<querytitle>unspecified</querytitle>" + 
254
        		"<returnfield>dataset/title</returnfield>" +
255
        		"<returndoctype>" + docType + "</returndoctype>" +
256
        		"<querygroup operator=\"UNION\">" +
257
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
258
        				"<value>" + titlePart + "</value>" +
259
        				"<pathexpr>dataset/title</pathexpr>" +
260
        			"</queryterm>" +
261
        		"</querygroup>" +
262
        	"</pathquery>";
263

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

    
288
                assertTrue(queryResult.contains(testTitle));
289
            }
290
            else {
291
                assertTrue(queryResult.indexOf("<error>") != -1);
292
            }
293
        }
294
        catch (MetacatInaccessibleException mie) {
295
            fail("Metacat Inaccessible:\n" + mie.getMessage());
296
        }
297
        catch (Exception e) {
298
            fail("General exception:\n" + e.getMessage());
299
        }
300

    
301
    }
302
	
303
	/*
304
	 * Retrus an access block base on params passed and the defaul perm order -
305
	 * allow first
306
	 */
307
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
308
			boolean write, boolean changePermission, boolean all) {
309
		return getAccessBlock(principal, grantAccess, read, write, changePermission, all,
310
				ALLOWFIRST);
311
	}
312

    
313
	/**
314
	 * This function returns an access block based on the params passed
315
	 */
316
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
317
			boolean write, boolean changePermission, boolean all, String permOrder) {
318
		String accessBlock = "<access "
319
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
320
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
321

    
322
		accessBlock += generateOneAccessRule(principal, grantAccess, read, write,
323
				changePermission, all);
324
		accessBlock += "</access>";
325

    
326
		return accessBlock;
327

    
328
	}
329

    
330
	/*
331
	 * Gets eml access block base on given acccess rules and perm order
332
	 */
333
	protected String getAccessBlock(Vector<String> accessRules, String permOrder) {
334
		String accessBlock = "<access "
335
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
336
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
337
		// adding rules
338
		if (accessRules != null && !accessRules.isEmpty()) {
339
			for (int i = 0; i < accessRules.size(); i++) {
340
				String rule = (String) accessRules.elementAt(i);
341
				accessBlock += rule;
342

    
343
			}
344
		}
345
		accessBlock += "</access>";
346
		return accessBlock;
347
	}
348

    
349
	/*
350
	 * Generates a access rule for given parameter. Note this xml portion
351
	 * doesn't include <access></access>
352
	 */
353
	protected String generateOneAccessRule(String principal, boolean grantAccess,
354
			boolean read, boolean write, boolean changePermission, boolean all) {
355
		String accessBlock = "";
356

    
357
		if (grantAccess) {
358
			accessBlock = "<allow>";
359
		} else {
360
			accessBlock = "<deny>";
361
		}
362

    
363
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
364

    
365
		if (all) {
366
			accessBlock += "<permission>all</permission>";
367
		} else {
368
			if (read) {
369
				accessBlock += "<permission>read</permission>";
370
			}
371
			if (write) {
372
				accessBlock += "<permission>write</permission>";
373
			}
374
			if (changePermission) {
375
				accessBlock += "<permission>changePermission</permission>";
376
			}
377
		}
378

    
379
		if (grantAccess) {
380
			accessBlock += "</allow>";
381
		} else {
382
			accessBlock += "</deny>";
383
		}
384
		return accessBlock;
385

    
386
	}
387
	
388
    /**
389
     * This function returns a valid eml document with public read access
390
     */
391
    protected String getTestEmlDoc(String title, String emlVersion) {
392

    
393
        String testDocument = "";
394

    
395
        String header;
396
		if (emlVersion == EML2_0_1) {
397
			header = testEml_201_Header;
398
		} else if (emlVersion == EML2_1_0) {
399
			header = testEml_210_Header;
400
		} else { // if (emlVersion == EML2_1_1) {
401
			header = testEml_211_Header;
402
		}
403
        
404
        testDocument += header;
405
        
406
        // if this is an EML 2.1.0 or later document, the document level access is
407
        // before the dataset element.
408
        if (emlVersion == EML2_1_0 || emlVersion == EML2_1_1) {
409
        	testDocument += getAccessBlock("public", true, true, false, false, false);
410
        }
411
        testDocument += "<dataset scope=\"document\"><title>" + title + "</title>"
412
				+ testEmlCreatorBlock;
413

    
414
        testDocument += testEmlContactBlock;
415
        
416
        // if this is an EML 2.0.1 or earlier document, the document level access is
417
        // inside the dataset element.
418
        if (emlVersion != EML2_1_0 && emlVersion != EML2_1_1) {
419
        	testDocument += getAccessBlock("public", true, true, false, false, false);
420
        }
421
        testDocument += "</dataset>";
422
        testDocument += "</eml:eml>";
423

    
424
        return testDocument;
425
    }
426

    
427
	/**
428
	 * This function returns a valid eml document with no access rules 
429
	 */
430
	protected String getTestEmlDoc(String title, String emlVersion, String inlineData1,
431
			String inlineData2, String onlineUrl1, String onlineUrl2,
432
			String docAccessBlock, String inlineAccessBlock1, String inlineAccessBlock2,
433
			String onlineAccessBlock1, String onlineAccessBlock2) {
434

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

    
463
		if (inlineData1 != null) {
464
			testDocument = testDocument
465
					+ "<distribution scope=\"document\" id=\"inlineEntity1\">"
466
					+ inlineData1 + "</distribution>";
467
		}
468
		if (inlineData2 != null) {
469
			testDocument = testDocument
470
					+ "<distribution scope=\"document\" id=\"inlineEntity2\">"
471
					+ inlineData2 + "</distribution>";
472
		}
473
		if (onlineUrl1 != null) {
474
			testDocument = testDocument
475
					+ "<distribution scope=\"document\" id=\"onlineEntity1\">"
476
					+ "<online><url function=\"download\">" + onlineUrl1
477
					+ "</url></online></distribution>";
478
		}
479
		if (onlineUrl2 != null) {
480
			testDocument = testDocument
481
					+ "<distribution scope=\"document\" id=\"onlineEntity2\">"
482
					+ "<online><url function=\"download\">" + onlineUrl2
483
					+ "</url></online></distribution>";
484
		}
485
		testDocument += testEmlContactBlock;
486

    
487
		// if this is a 2.0.X document, the document level access block sits
488
		// inside the dataset element.
489
		if (docAccessBlock != null && 
490
				(emlVersion.equals(EML2_0_0) || emlVersion.equals(EML2_0_1))) {
491
			testDocument += docAccessBlock;
492
		}
493

    
494
		testDocument += "</dataset>";
495

    
496
		if (inlineAccessBlock1 != null) {
497
			testDocument += "<additionalMetadata>";
498
			testDocument += "<describes>inlineEntity1</describes>";
499
			testDocument += inlineAccessBlock1;
500
			testDocument += "</additionalMetadata>";
501
		}
502

    
503
		if (inlineAccessBlock2 != null) {
504
			testDocument += "<additionalMetadata>";
505
			testDocument += "<describes>inlineEntity2</describes>";
506
			testDocument += inlineAccessBlock2;
507
			testDocument += "</additionalMetadata>";
508
		}
509

    
510
		if (onlineAccessBlock1 != null) {
511
			testDocument += "<additionalMetadata>";
512
			testDocument += "<describes>onlineEntity1</describes>";
513
			testDocument += onlineAccessBlock1;
514
			testDocument += "</additionalMetadata>";
515
		}
516

    
517
		if (onlineAccessBlock2 != null) {
518
			testDocument += "<additionalMetadata>";
519
			testDocument += "<describes>onlineEntity2</describes>";
520
			testDocument += onlineAccessBlock2;
521
			testDocument += "</additionalMetadata>";
522
		}
523

    
524
		testDocument += "</eml:eml>";
525

    
526
		// System.out.println("Returning following document" + testDocument);
527
		return testDocument;
528
	}
529
	
530
	/**
531
	 * 
532
	 */
533
	protected String getTestDocFromFile(String filePath) throws IOException{
534
		StringBuffer output = new StringBuffer();
535
		
536
		FileReader fileReader = new FileReader(new File(filePath));
537
		BufferedReader bufferedReader = new BufferedReader(fileReader);
538
		String readLine = null;
539
		
540
		while ((readLine = bufferedReader.readLine()) != null) {
541
			output.append(readLine);
542
		}
543
		
544
		return output.toString();
545
	}
546

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

    
589
		DBConnectionPool connPool = DBConnectionPool.getInstance();
590
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
591
		int serialNumber = dbconn.getCheckOutSerialNumber();
592

    
593
		PreparedStatement pstmt = null;
594

    
595
		debug("Selecting from db: " + sqlStatement);
596
		pstmt = dbconn.prepareStatement(sqlStatement);
597
		pstmt.execute();
598

    
599
		ResultSet resultSet = pstmt.getResultSet();
600
		ResultSetMetaData rsMetaData = resultSet.getMetaData();
601
		int numColumns = rsMetaData.getColumnCount();
602
		debug("Number of data columns: " + numColumns);
603
		while (resultSet.next()) {
604
			Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
605
			for (int i = 1; i <= numColumns; i++) {
606
				if (resultSet.getObject(i) != null) {
607
					hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i));
608
				}
609
			}
610
			debug("adding data row to result vector");
611
			resultVector.add(hashTable);
612
		}
613

    
614
		resultSet.close();
615
		pstmt.close();
616
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
617

    
618
		return resultVector;
619
	}
620
	
621
	protected static void dbQuery(String sqlStatement, String methodName)
622
			throws SQLException {
623

    
624
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
625
		int serialNumber = dbconn.getCheckOutSerialNumber();
626

    
627
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
628
		debug("Executing against db: " + sqlStatement);
629
		statement.executeQuery();
630

    
631
		statement.close();
632
		
633
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
634
	}
635
	
636
	protected static void dbUpdate(String sqlStatement, String methodName)
637
			throws SQLException {
638

    
639
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
640
		int serialNumber = dbconn.getCheckOutSerialNumber();
641

    
642
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
643
		debug("Executing against db: " + sqlStatement);
644
		statement.executeUpdate();
645
		statement.close();
646

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

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

    
713
	/**
714
	 * Insert a document into metacat. The expected result is passed as result
715
	 */
716

    
717
	protected String uploadDocumentId(String docid, String filePath, boolean result,
718
			boolean expectedKarmaException) {
719
		debug("uploadDocumentId() - docid=" + docid + " filePath=" + filePath
720
				+ " expectedResult=" + result + " expectedKarmaException="
721
				+ expectedKarmaException);
722
		String response = null;
723
		try {
724
			response = m.upload(docid, new File(filePath));
725
			if (result) {
726
				assertTrue(response, (response.indexOf("<success>") != -1));
727
				assertTrue(response, response.indexOf(docid) != -1);
728
			} else {
729
				assertTrue(response, (response.indexOf("<success>") == -1));
730
			}
731
			debug("uploadDocid():  response=" + response);
732
		} catch (MetacatInaccessibleException mie) {
733
			fail("Metacat Inaccessible:\n" + mie.getMessage());
734
		} catch (InsufficientKarmaException ike) {
735
			if (!expectedKarmaException) {
736
				fail("Insufficient karma:\n" + ike.getMessage());
737
			}
738
		} catch (MetacatException me) {
739
			if (result) {
740
				fail("Metacat Error:\n" + me.getMessage());
741
			} else {
742
				debug("Metacat Error:\n" + me.getMessage());
743
			}
744
		} catch (Exception e) {
745
			fail("General exception:\n" + e.getMessage());
746
		}
747
		return response;
748
	}
749

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

    
784
		return response;
785
	}
786

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

    
835
				if (!testDoc.equals(doc)) {
836
					System.out.println("doc ***********************");
837
					System.out.println(doc);
838
					System.out.println("end doc ***********************");
839
					System.out.println("testDoc ***********************");
840
					System.out.println(testDoc);
841
					System.out.println("end testDoc ***********************");
842
				}
843

    
844
				assertTrue(testDoc.equals(doc));
845
			} else {
846
				assertTrue(doc.indexOf("<error>") != -1);
847
			}
848
		} catch (MetacatInaccessibleException mie) {
849
			fail("Metacat Inaccessible:\n" + mie.getMessage());
850
		} catch (InsufficientKarmaException ike) {
851
			if (!expectedKarmaFailure) {
852
				fail("Insufficient karma:\n" + ike.getMessage());
853
			}
854
		} catch (MetacatException me) {
855
			fail("Metacat Error:\n" + me.getMessage());
856
		} catch (Exception e) {
857
			fail("General exception:\n" + e.getMessage());
858
		}
859

    
860
	}
861

    
862
}
    (1-1/1)