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-03-04 09:47:28 -0800 (Tue, 04 Mar 2014) $'
9
 * '$Revision: 8694 $'
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
	protected static String piscouser;
105
	protected static String piscopassword;
106
	
107
	protected static String metacatContextDir;
108
	
109
	static {
110
		try {
111
			SortedProperties testProperties = 
112
				new SortedProperties("build/tests/test.properties");
113
			testProperties.load();
114
			metacatContextDir = testProperties.getProperty("metacat.contextDir");
115
			PropertyService.getInstance(metacatContextDir + "/WEB-INF");
116
//			PropertyService.getInstance();
117
		    String printDebugString = PropertyService.getProperty("test.printdebug");
118
		    printDebug = Boolean.parseBoolean(printDebugString);
119

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

    
213
	protected String testEmlCreatorBlock = "<creator scope=\"document\">                                       "
214
			+ " <individualName>                                                  "
215
			+ "    <surName>Smith</surName>                                       "
216
			+ " </individualName>                                                 "
217
			+ "</creator>                                                         ";
218

    
219
	protected String testEmlContactBlock = "<contact scope=\"document\">                                       "
220
			+ " <individualName>                                                  "
221
			+ "    <surName>Jackson</surName>                                     "
222
			+ " </individualName>                                                 "
223
			+ "</contact>                                                         ";
224

    
225
	protected String testEmlInlineBlock1 = "<inline>                                                           "
226
			+ "  <admin>                                                          "
227
			+ "    <contact>                                                      "
228
			+ "      <name>Operator</name>                                        "
229
			+ "      <institution>PSI</institution>                               "
230
			+ "    </contact>                                                     "
231
			+ "  </admin>                                                         "
232
			+ "</inline>                                                          ";
233

    
234
	protected String testEmlInlineBlock2 = "<inline>                                                           "
235
			+ "  <instrument>                                                     "
236
			+ "    <instName>LCQ</instName>                                       "
237
			+ "    <source type=\"ESI\"></source>                                 "
238
			+ "    <detector type=\"EM\"></detector>                              "
239
			+ "  </instrument>                                                    "
240
			+ "</inline>                                                          ";
241

    
242
    
243
    /**
244
     * Returns an xml squery that searches for the doc id in the
245
     * title of documents. This function is for eml-2.0.1+ only. For 
246
     * other eml versions, this function might have to modified.
247
     */
248
    protected String getTestEmlQuery(String titlePart, String emlVersion) {
249

    
250
    	String docType;
251
    	if (emlVersion.equals(EML2_0_1)) {
252
    		docType = "eml://ecoinformatics.org/eml-2.0.1";
253
    	} else if (emlVersion.equals(EML2_1_0)) {
254
    		docType = "eml://ecoinformatics.org/eml-2.1.0";
255
    	} else { //if (emlVersion.equals(EML2_1_1)) {
256
    		docType = "eml://ecoinformatics.org/eml-2.1.1";
257
    	}
258
    	
259
        String sQuery = "";
260
        sQuery = 
261
        	"<pathquery version=\"1.0\">" +
262
        		"<meta_file_id>unspecified</meta_file_id>" +
263
        		"<querytitle>unspecified</querytitle>" + 
264
        		"<returnfield>dataset/title</returnfield>" +
265
        		"<returndoctype>" + docType + "</returndoctype>" +
266
        		"<querygroup operator=\"UNION\">" +
267
        			"<queryterm casesensitive=\"false\" searchmode=\"contains\">" +
268
        				"<value>" + titlePart + "</value>" +
269
        				"<pathexpr>dataset/title</pathexpr>" +
270
        			"</queryterm>" +
271
        		"</querygroup>" +
272
        	"</pathquery>";
273

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

    
298
                assertTrue(queryResult.contains(testTitle));
299
            }
300
            else {
301
                assertTrue(queryResult.indexOf("<error>") != -1);
302
            }
303
        }
304
        catch (MetacatInaccessibleException mie) {
305
            fail("Metacat Inaccessible:\n" + mie.getMessage());
306
        }
307
        catch (Exception e) {
308
            fail("General exception:\n" + e.getMessage());
309
        }
310

    
311
    }
312
	
313
	/*
314
	 * Retrus an access block base on params passed and the defaul perm order -
315
	 * allow first
316
	 */
317
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
318
			boolean write, boolean changePermission, boolean all) {
319
		return getAccessBlock(principal, grantAccess, read, write, changePermission, all,
320
				ALLOWFIRST);
321
	}
322

    
323
	/**
324
	 * This function returns an access block based on the params passed
325
	 */
326
	protected String getAccessBlock(String principal, boolean grantAccess, boolean read,
327
			boolean write, boolean changePermission, boolean all, String permOrder) {
328
		String accessBlock = "<access "
329
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
330
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
331

    
332
		accessBlock += generateOneAccessRule(principal, grantAccess, read, write,
333
				changePermission, all);
334
		accessBlock += "</access>";
335

    
336
		return accessBlock;
337

    
338
	}
339

    
340
	/*
341
	 * Gets eml access block base on given acccess rules and perm order
342
	 */
343
	protected String getAccessBlock(Vector<String> accessRules, String permOrder) {
344
		String accessBlock = "<access "
345
				+ "authSystem=\"ldap://ldap.ecoinformatics.org:389/dc=ecoinformatics,dc=org\""
346
				+ " order=\"" + permOrder + "\"" + " scope=\"document\"" + ">";
347
		// adding rules
348
		if (accessRules != null && !accessRules.isEmpty()) {
349
			for (int i = 0; i < accessRules.size(); i++) {
350
				String rule = (String) accessRules.elementAt(i);
351
				accessBlock += rule;
352

    
353
			}
354
		}
355
		accessBlock += "</access>";
356
		return accessBlock;
357
	}
358

    
359
	/*
360
	 * Generates a access rule for given parameter. Note this xml portion
361
	 * doesn't include <access></access>
362
	 */
363
	protected String generateOneAccessRule(String principal, boolean grantAccess,
364
			boolean read, boolean write, boolean changePermission, boolean all) {
365
		String accessBlock = "";
366

    
367
		if (grantAccess) {
368
			accessBlock = "<allow>";
369
		} else {
370
			accessBlock = "<deny>";
371
		}
372

    
373
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
374

    
375
		if (all) {
376
			accessBlock += "<permission>all</permission>";
377
		} else {
378
			if (read) {
379
				accessBlock += "<permission>read</permission>";
380
			}
381
			if (write) {
382
				accessBlock += "<permission>write</permission>";
383
			}
384
			if (changePermission) {
385
				accessBlock += "<permission>changePermission</permission>";
386
			}
387
		}
388

    
389
		if (grantAccess) {
390
			accessBlock += "</allow>";
391
		} else {
392
			accessBlock += "</deny>";
393
		}
394
		return accessBlock;
395

    
396
	}
397
	
398
    /**
399
     * This function returns a valid eml document with public read access
400
     */
401
    protected String getTestEmlDoc(String title, String emlVersion) {
402

    
403
        String testDocument = "";
404

    
405
        String header;
406
		if (emlVersion == EML2_0_1) {
407
			header = testEml_201_Header;
408
		} else if (emlVersion == EML2_1_0) {
409
			header = testEml_210_Header;
410
		} else { // if (emlVersion == EML2_1_1) {
411
			header = testEml_211_Header;
412
		}
413
        
414
        testDocument += header;
415
        
416
        // if this is an EML 2.1.0 or later document, the document level access is
417
        // before 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 scope=\"document\"><title>" + title + "</title>"
422
				+ testEmlCreatorBlock;
423

    
424
        testDocument += testEmlContactBlock;
425
        
426
        // if this is an EML 2.0.1 or earlier document, the document level access is
427
        // inside the dataset element.
428
        if (emlVersion != EML2_1_0 && emlVersion != EML2_1_1) {
429
        	testDocument += getAccessBlock("public", true, true, false, false, false);
430
        }
431
        testDocument += "</dataset>";
432
        testDocument += "</eml:eml>";
433

    
434
        return testDocument;
435
    }
436

    
437
	/**
438
	 * This function returns a valid eml document with no access rules 
439
	 */
440
	protected String getTestEmlDoc(String title, String emlVersion, String inlineData1,
441
			String inlineData2, String onlineUrl1, String onlineUrl2,
442
			String docAccessBlock, String inlineAccessBlock1, String inlineAccessBlock2,
443
			String onlineAccessBlock1, String onlineAccessBlock2) {
444

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

    
473
		if (inlineData1 != null) {
474
			testDocument = testDocument
475
					+ "<distribution scope=\"document\" id=\"inlineEntity1\">"
476
					+ inlineData1 + "</distribution>";
477
		}
478
		if (inlineData2 != null) {
479
			testDocument = testDocument
480
					+ "<distribution scope=\"document\" id=\"inlineEntity2\">"
481
					+ inlineData2 + "</distribution>";
482
		}
483
		if (onlineUrl1 != null) {
484
			testDocument = testDocument
485
					+ "<distribution scope=\"document\" id=\"onlineEntity1\">"
486
					+ "<online><url function=\"download\">" + onlineUrl1
487
					+ "</url></online></distribution>";
488
		}
489
		if (onlineUrl2 != null) {
490
			testDocument = testDocument
491
					+ "<distribution scope=\"document\" id=\"onlineEntity2\">"
492
					+ "<online><url function=\"download\">" + onlineUrl2
493
					+ "</url></online></distribution>";
494
		}
495
		testDocument += testEmlContactBlock;
496

    
497
		// if this is a 2.0.X document, the document level access block sits
498
		// inside the dataset element.
499
		if (docAccessBlock != null && 
500
				(emlVersion.equals(EML2_0_0) || emlVersion.equals(EML2_0_1))) {
501
			testDocument += docAccessBlock;
502
		}
503

    
504
		testDocument += "</dataset>";
505

    
506
		if (inlineAccessBlock1 != null) {
507
			testDocument += "<additionalMetadata>";
508
			testDocument += "<describes>inlineEntity1</describes>";
509
			testDocument += inlineAccessBlock1;
510
			testDocument += "</additionalMetadata>";
511
		}
512

    
513
		if (inlineAccessBlock2 != null) {
514
			testDocument += "<additionalMetadata>";
515
			testDocument += "<describes>inlineEntity2</describes>";
516
			testDocument += inlineAccessBlock2;
517
			testDocument += "</additionalMetadata>";
518
		}
519

    
520
		if (onlineAccessBlock1 != null) {
521
			testDocument += "<additionalMetadata>";
522
			testDocument += "<describes>onlineEntity1</describes>";
523
			testDocument += onlineAccessBlock1;
524
			testDocument += "</additionalMetadata>";
525
		}
526

    
527
		if (onlineAccessBlock2 != null) {
528
			testDocument += "<additionalMetadata>";
529
			testDocument += "<describes>onlineEntity2</describes>";
530
			testDocument += onlineAccessBlock2;
531
			testDocument += "</additionalMetadata>";
532
		}
533

    
534
		testDocument += "</eml:eml>";
535

    
536
		// System.out.println("Returning following document" + testDocument);
537
		return testDocument;
538
	}
539
	
540
	/**
541
	 * 
542
	 */
543
	protected String getTestDocFromFile(String filePath) throws IOException{
544
		StringBuffer output = new StringBuffer();
545
		
546
		FileReader fileReader = new FileReader(new File(filePath));
547
		BufferedReader bufferedReader = new BufferedReader(fileReader);
548
		String readLine = null;
549
		
550
		while ((readLine = bufferedReader.readLine()) != null) {
551
			output.append(readLine);
552
		}
553
		
554
		return output.toString();
555
	}
556

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

    
599
		DBConnectionPool connPool = DBConnectionPool.getInstance();
600
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
601
		int serialNumber = dbconn.getCheckOutSerialNumber();
602

    
603
		PreparedStatement pstmt = null;
604

    
605
		debug("Selecting from db: " + sqlStatement);
606
		pstmt = dbconn.prepareStatement(sqlStatement);
607
		pstmt.execute();
608

    
609
		ResultSet resultSet = pstmt.getResultSet();
610
		ResultSetMetaData rsMetaData = resultSet.getMetaData();
611
		int numColumns = rsMetaData.getColumnCount();
612
		debug("Number of data columns: " + numColumns);
613
		while (resultSet.next()) {
614
			Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
615
			for (int i = 1; i <= numColumns; i++) {
616
				if (resultSet.getObject(i) != null) {
617
					hashTable.put(rsMetaData.getColumnName(i), resultSet.getObject(i));
618
				}
619
			}
620
			debug("adding data row to result vector");
621
			resultVector.add(hashTable);
622
		}
623

    
624
		resultSet.close();
625
		pstmt.close();
626
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
627

    
628
		return resultVector;
629
	}
630
	
631
	protected static void dbQuery(String sqlStatement, String methodName)
632
			throws SQLException {
633

    
634
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
635
		int serialNumber = dbconn.getCheckOutSerialNumber();
636

    
637
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
638
		debug("Executing against db: " + sqlStatement);
639
		statement.executeQuery();
640

    
641
		statement.close();
642
		
643
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
644
	}
645
	
646
	protected static void dbUpdate(String sqlStatement, String methodName)
647
			throws SQLException {
648

    
649
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
650
		int serialNumber = dbconn.getCheckOutSerialNumber();
651

    
652
		PreparedStatement statement = dbconn.prepareStatement(sqlStatement);
653
		debug("Executing against db: " + sqlStatement);
654
		statement.executeUpdate();
655
		statement.close();
656

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

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

    
723
	/**
724
	 * Insert a document into metacat. The expected result is passed as result
725
	 */
726

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

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

    
794
		return response;
795
	}
796

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

    
845
				if (!testDoc.equals(doc)) {
846
					System.out.println("doc ***********************");
847
					System.out.println(doc);
848
					System.out.println("end doc ***********************");
849
					System.out.println("testDoc ***********************");
850
					System.out.println(testDoc);
851
					System.out.println("end testDoc ***********************");
852
				}
853

    
854
				assertTrue(testDoc.equals(doc));
855
			} else {
856
				assertTrue(doc.indexOf("<error>") != -1);
857
			}
858
		} catch (MetacatInaccessibleException mie) {
859
			fail("Metacat Inaccessible:\n" + mie.getMessage());
860
		} catch (InsufficientKarmaException ike) {
861
			if (!expectedKarmaFailure) {
862
				fail("Insufficient karma:\n" + ike.getMessage());
863
			}
864
		} catch (MetacatException me) {
865
			fail("Metacat Error:\n" + me.getMessage());
866
		} catch (Exception e) {
867
			fail("General exception:\n" + e.getMessage());
868
		}
869

    
870
	}
871

    
872
}
    (1-1/1)