Project

General

Profile

1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2008 Regents of the University of California and the
4
 *              National Center for Ecological Analysis and Synthesis
5
 *  Purpose: To test the Access Controls in metacat by JUnit
6
 *
7
 *   '$Author: leinfelder $'
8
 *     '$Date: 2011-12-15 17:32:39 -0800 (Thu, 15 Dec 2011) $'
9
 * '$Revision: 6790 $'
10
 *
11
 * This program is free software; you can redistribute it and/or modify
12
 * it under the terms of the GNU General Public License as published by
13
 * the Free Software Foundation; either version 2 of the License, or
14
 * (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU General Public License
22
 * along with this program; if not, write to the Free Software
23
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24
 */
25

    
26
package edu.ucsb.nceas;
27

    
28
import java.io.BufferedReader;
29
import java.io.File;
30
import java.io.FileReader;
31
import java.io.IOException;
32
import java.io.InputStreamReader;
33
import java.io.Reader;
34
import java.io.StringReader;
35
import java.sql.PreparedStatement;
36
import java.sql.ResultSet;
37
import java.sql.ResultSetMetaData;
38
import java.sql.SQLException;
39
import java.util.HashMap;
40
import java.util.Hashtable;
41
import java.util.Vector;
42

    
43
import junit.framework.TestCase;
44

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
278
		return accessBlock;
279

    
280
	}
281

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

    
295
			}
296
		}
297
		accessBlock += "</access>";
298
		return accessBlock;
299
	}
300

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

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

    
315
		accessBlock = accessBlock + "<principal>" + principal + "</principal>";
316

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

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

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

    
345
        String testDocument = "";
346

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

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

    
376
        return testDocument;
377
    }
378

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

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

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

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

    
446
		testDocument += "</dataset>";
447

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

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

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

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

    
476
		testDocument += "</eml:eml>";
477

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

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

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

    
545
		PreparedStatement pstmt = null;
546

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

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

    
566
		resultSet.close();
567
		pstmt.close();
568
		DBConnectionPool.returnDBConnection(dbconn, serialNumber);
569

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

    
576
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
577
		int serialNumber = dbconn.getCheckOutSerialNumber();
578

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

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

    
591
		DBConnection dbconn = DBConnectionPool.getDBConnection(methodName);
592
		int serialNumber = dbconn.getCheckOutSerialNumber();
593

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

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

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

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

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

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

    
736
		return response;
737
	}
738

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

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

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

    
812
	}
813

    
814
}
    (1-1/1)