Project

General

Profile

« Previous | Next » 

Revision 4080

Added by daigle almost 16 years ago

Merge 1.9 changes into Head

View differences:

MetaCatServletNetTest.java
27 27
package edu.ucsb.nceas.metacatnettest;
28 28

  
29 29
import edu.ucsb.nceas.metacat.*;
30
import edu.ucsb.nceas.metacat.service.PropertyService;
31
import edu.ucsb.nceas.metacat.util.SystemUtil;
30 32
import edu.ucsb.nceas.utilities.Options;
33
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
31 34
import edu.ucsb.nceas.morpho.framework.*;
32 35
import junit.framework.Test;
33 36
import junit.framework.TestCase;
......
40 43

  
41 44
import org.apache.log4j.Logger;
42 45

  
43

  
44 46
/**
45 47
 * A JUnit test for testing Step class processing
46 48
 */
47
public class MetaCatServletNetTest extends TestCase
48
{
49
  static
50
  {
51
	  try
52
	  {
53
		  Options.initialize(new File("build/tests/metacat.properties"));
54
	  }
55
	  catch(Exception e)
56
	  {
57
		  System.err.println("Exception in initialize option in MetacatServletNetTest "+e.getMessage());
58
	  }
59
  }
60
  
61
  private String metacatURL=MetaCatUtil.getOption("junittesturl");
62
  private String serialNumber;
63
  private static Logger logMetacat = Logger.getLogger(DocumentImpl.class);
64
  /**
65
   * Constructor to build the test
66
   *
67
   * @param name the name of the test method
68
   */
69
  public MetaCatServletNetTest(String name)
70
  {
71
    super(name);
72
  }
49
public class MetaCatServletNetTest extends TestCase {
50
	private static String metacatURL;
51
	static {
52
		try {
53
			metacatURL = SystemUtil.getServletURL();
54
			Options.initialize(new File("build/tests/metacat.properties"));
55
		} catch (PropertyNotFoundException pnfe) {
56
			System.err.println("could not find metacat URL in MetacatServletNetTest: "
57
					+ pnfe.getMessage());
58
		} catch (Exception e) {
59
			System.err.println("Exception in initialize option in MetacatServletNetTest: "
60
					+ e.getMessage());
61
		}
62
	}
73 63

  
74
 /**
75
   * Constructor to build the test
76
   *
77
   * @param name the name of the test method
78
   */
79
  public MetaCatServletNetTest(String name, String serial)
80
  {
81
    super(name);
82
    serialNumber=serial;
83
  }
84
  /**
85
   * Establish a testing framework by initializing appropriate objects
86
   */
87
  public void setUp()
88
 {
89
    
90
 }
64
	private String serialNumber;
65
	private static Logger logMetacat = Logger.getLogger(DocumentImpl.class);
91 66

  
92
  /**
93
   * Release any objects after tests are complete
94
   */
95
  public void tearDown()
96
  {
97
  }
67
	/**
68
	 * Constructor to build the test
69
	 *
70
	 * @param name the name of the test method
71
	 */
72
	public MetaCatServletNetTest(String name) {
73
		super(name);
74
	}
98 75

  
99
  /**
100
   * Create a suite of tests to be run together
101
   */
102
  public static Test suite()
103
  {
104
    double number = 0;
105
    String serial = null;
106
    
107
    
108
    TestSuite suite = new TestSuite();
109
    suite.addTest(new MetaCatServletNetTest("initialize"));
110
    suite.addTest(new MetaCatServletNetTest("testNCEASLoginFail"));
111
    //Should put a login successfully at the end of login test
112
    //So insert or update can have cookie.
113
    suite.addTest(new MetaCatServletNetTest("testNCEASLogin"));
114
    
115
    //create random number for docid, so it can void repeat
116
    number = Math.random()*100000;
117
    serial = Integer.toString(((new Double(number)).intValue()));
118
    logMetacat.info("serial: "+serial);
119
    suite.addTest(new MetaCatServletNetTest("testInsertXMLDocument", serial));
120
    suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentXMLFormat", 
121
                                                        serial));
122
    suite.addTest(new MetaCatServletNetTest("testUpdateXMLDocument",serial));    
123
    suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentHTMLFormat", 
124
                                                        serial));
125
    suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentZipFormat", 
126
                                                        serial));
127
    
128
    suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument",serial));
129
    
130
    //insert invalid xml document
131
    number = Math.random()*100000;
132
    serial = Integer.toString(((new Double(number)).intValue()));
133
    suite.addTest(new MetaCatServletNetTest("testInsertInvalidateXMLDocument",
134
                                                                  serial));    
135
    //insert non well formed document
136
    number = Math.random()*100000;
137
    serial = Integer.toString(((new Double(number)).intValue())); 
138
   suite.addTest(new MetaCatServletNetTest("testInsertNonWellFormedXMLDocument",
139
                                                            serial));
140
    //insert data file  
141
    number = Math.random()*100000;
142
    serial = Integer.toString(((new Double(number)).intValue()));
143
    suite.addTest(new MetaCatServletNetTest("testLogOut"));                   
144
                              
145
    return suite;
146
  }
147
  
76
	/**
77
	 * Constructor to build the test
78
	 *
79
	 * @param name the name of the test method
80
	 */
81
	public MetaCatServletNetTest(String name, String serial) {
82
		super(name);
83
		serialNumber = serial;
84
	}
148 85

  
86
	/**
87
	 * Establish a testing framework by initializing appropriate objects
88
	 */
89
	public void setUp() {
149 90

  
150
  /**
151
   * Run an initial test that always passes to check that the test
152
   * harness is working.
153
   */
154
  public void initialize()
155
  {
156
    assertTrue(1 == 1);
157
  }
91
	}
158 92

  
159
  /**
160
   * Test the login to neceas succesfully
161
   */
162
  public void testNCEASLogin()
163
  {
164
    String user="uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
165
    String passwd="123456";
166
    assertTrue(logIn(user,passwd));
167
    //assertTrue( withProtocol.getProtocol().equals("http"));
168
  }
169
  
170
  /**
171
   * Test the login to neceas failed
172
   */
173
  public void testNCEASLoginFail()
174
  {
175
    String user="uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
176
    String passwd="12345678";
177
    assertTrue(!logIn(user,passwd));
178
    
179
  }
180
  
93
	/**
94
	 * Release any objects after tests are complete
95
	 */
96
	public void tearDown() {
97
	}
181 98

  
182
  
183
  /**
184
   * Test the login to lter failed
185
   */
186
  public void testLterReferralLoginFail()
187
  {
188
    String user="uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
189
    String passwd="qVyGpveb";
190
    assertTrue(!logIn(user,passwd));
191
    //assertTrue( withProtocol.getProtocol().equals("http"));
192
  }
193
  
194
  
195
 /**
196
   * Test insert a xml document successfully
197
   */
198
  public void testInsertXMLDocument()
199
  {
200
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
201
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
202
    logMetacat.info("insert docid: "+name);
203
    String content="<?xml version=\"1.0\"?>"
204
                   +"<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
205
                   +"eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
206
                   +"edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
207
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
208
                   +"<identifier>"+name+"</identifier>"
209
                   +"<allow>"
210
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
211
                   +"<permission>all</permission>"
212
                   +"</allow>"
213
                   +"<allow>"
214
                   +"<principal>public</principal>"
215
                   +"<permission>read</permission>"
216
                   +"</allow>"
217
                   +"</acl>";
218
    logMetacat.info("xml document: "+content);
219
     assertTrue(handleXMLDocument(content, name, "insert"));
220
   
221
  }
222
  
223
  /**
224
   * Test insert a invalidate xml document successfully
225
   * In the String, there is no <!Doctype ... Public/System/>
226
   */
227
  public void testInsertInvalidateXMLDocument()
228
  {
229
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
230
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
231
    logMetacat.info("insert docid: "+name);
232
    String content="<?xml version=\"1.0\"?>"
233
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
234
                   +"<identifier>"+name+"</identifier>"
235
                   +"<allow>"
236
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
237
                   +"<permission>all</permission>"
238
                   +"</allow>"
239
                   +"<allow>"
240
                   +"<principal>public</principal>"
241
                   +"<permission>read</permission>"
242
                   +"</allow>"
243
                   +"</acl>";
244
    logMetacat.info("xml document: "+content);
245
     assertTrue(handleXMLDocument(content, name, "insert"));
246
  }
247
  
248
   /**
249
   * Test insert a non well-formed xml document successfully
250
   * There is no </acl> in this string
251
   */
252
  public void testInsertNonWellFormedXMLDocument()
253
  {
254
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
255
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
256
    logMetacat.info("insert non well-formed docid: "+name);
257
    String content="<?xml version=\"1.0\"?>"
258
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
259
                   +"<identifier>"+name+"</identifier>"
260
                   +"<allow>"
261
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
262
                   +"<permission>all</permission>"
263
                   +"</allow>"
264
                   +"<allow>"
265
                   +"<principal>public</principal>"
266
                   +"<permission>read</permission>"
267
                   +"</allow>";
268
  
269
     logMetacat.info("xml document: "+content);
270
     assertTrue(!handleXMLDocument(content, name, "insert"));
271
  } 
99
	/**
100
	 * Create a suite of tests to be run together
101
	 */
102
	public static Test suite() {
103
		double number = 0;
104
		String serial = null;
272 105

  
273
  /**
274
   * Test read a xml document  in xml format successfully
275
   */
276
  public void testReadXMLDocumentXMLFormat()
277
  {
278
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
279
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
280
    assertTrue(handleReadAction(name, "xml"));
281
   
282
  } 
106
		TestSuite suite = new TestSuite();
107
		suite.addTest(new MetaCatServletNetTest("initialize"));
108
		suite.addTest(new MetaCatServletNetTest("testNCEASLoginFail"));
109
		//Should put a login successfully at the end of login test
110
		//So insert or update can have cookie.
111
		suite.addTest(new MetaCatServletNetTest("testNCEASLogin"));
283 112

  
284
  /**
285
   * Test read a xml document  in html format successfully
286
   */
287
  public void testReadXMLDocumentHTMLFormat()
288
  {
289
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
290
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
291
    assertTrue(handleReadAction(name, "html"));
292
   
293
  }
113
		//create random number for docid, so it can void repeat
114
		number = Math.random() * 100000;
115
		serial = Integer.toString(((new Double(number)).intValue()));
116
		logMetacat.info("serial: " + serial);
117
		suite.addTest(new MetaCatServletNetTest("testInsertXMLDocument", serial));
118
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentXMLFormat", serial));
119
		suite.addTest(new MetaCatServletNetTest("testUpdateXMLDocument", serial));
120
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentHTMLFormat", serial));
121
		suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentZipFormat", serial));
294 122

  
295
 
296
  /**
297
   * Test read a xml document  in zip format successfully
298
   */
299
  public void testReadXMLDocumentZipFormat()
300
  {
301
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
302
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
303
    assertTrue(handleReadAction(name, "zip"));
304
   
305
  }
306
  
307
  /**
308
   * Test insert a xml document successfully
309
   */
310
  public void testUpdateXMLDocument()
311
  {
312
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
313
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"2";
314
    logMetacat.info("update docid: "+name);
315
    String content="<?xml version=\"1.0\"?>"
316
                   +"<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
317
                   +"eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
318
                   +"edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
319
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
320
                   +"<identifier>"+name+"</identifier>"
321
                   +"<allow>"
322
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
323
                   +"<permission>all</permission>"
324
                   +"</allow>"
325
                   +"<allow>"
326
                   +"<principal>public</principal>"
327
                   +"<permission>read</permission>"
328
                   +"</allow>"
329
                   +"</acl>";
330
     logMetacat.info("xml document: "+content);
331
     assertTrue(handleXMLDocument(content, name, "update"));
332
   
333
  }
334
  
335
  /**
336
   * Test insert a data file successfully
337
   */
338
  public void testInertDataFile()
339
  {
340
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
341
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
342
    logMetacat.info("insert data file docid: "+name);
343
    logMetacat.info("insert data file ");
344
    File hello = new File("test/jones.204.22.xml");
345
   
346
    assertTrue(insertDataFile(name, hello));
347
  }
348
  
349
  /**
350
   * Test delete a xml document successfully
351
   */
352
  public void testDeleteXMLDocument()
353
  {
354
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
355
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"2";
356
    logMetacat.info("delete docid: "+name);
357
    assertTrue(handleDeleteFile(name));
358
   
359
  }
360
  
361
  
362
       
363
  /**
364
   * Test logout action
365
   */
366
  public void testLogOut()
367
  {
368
    
369
    assertTrue(handleLogOut());
370
   
371
  }
372
  
373
 /**
374
   * Method to hanld login action
375
   *
376
   * @param usrerName, the DN name of the test method
377
   * @param passWord, the passwd of the user
378
   */
379
  
380
  public boolean logIn(String userName, String passWord)
381
  {
382
    Properties prop = new Properties();
383
    prop.put("action", "login");
384
    prop.put("qformat", "xml");
385
    prop.put("username", userName);
386
    prop.put("password", passWord);
123
		suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument", serial));
387 124

  
388
    // Now contact metacat
389
    String response = getMetacatString(prop);
390
    logMetacat.info("Login Message: "+response);
391
    boolean connected = false;
392
    if (response.indexOf("<login>") != -1) {
393
      connected = true;
394
    } else {
395
      
396
      connected = false;
397
    }
125
		//insert invalid xml document
126
		number = Math.random() * 100000;
127
		serial = Integer.toString(((new Double(number)).intValue()));
128
		suite
129
				.addTest(new MetaCatServletNetTest("testInsertInvalidateXMLDocument",
130
						serial));
131
		//insert non well formed document
132
		number = Math.random() * 100000;
133
		serial = Integer.toString(((new Double(number)).intValue()));
134
		suite.addTest(new MetaCatServletNetTest("testInsertNonWellFormedXMLDocument",
135
				serial));
136
		//insert data file  
137
		number = Math.random() * 100000;
138
		serial = Integer.toString(((new Double(number)).intValue()));
139
		suite.addTest(new MetaCatServletNetTest("testLogOut"));
398 140

  
399
    return connected;
400
  }
401
  
402
  /**
403
   * Method to hanld logout action
404
   *
405
   * @param usrerName, the DN name of the test method
406
   * @param passWord, the passwd of the user
407
   */
408
  
409
  public boolean handleLogOut()
410
  {
411
    boolean disConnected =false;
412
    Properties prop = new Properties();
413
    prop.put("action", "logout");
414
    prop.put("qformat", "xml");
415
  
416
    String response = getMetacatString(prop);
417
    logMetacat.info("Logout Message: "+response);
418
    edu.ucsb.nceas.morpho.framework.HttpMessage.setCookie(null);
419
     
420
    if (response.indexOf("<logout>") != -1) 
421
    {
422
      disConnected = true;
423
    } 
424
    else 
425
    {
426
      disConnected = false;
427
    }
141
		return suite;
142
	}
428 143

  
429
    return disConnected;
430
  }
431
  
432
  /**
433
   * Method to hanld read both xml and data file
434
   *
435
   * @param docid, the docid of the document want to read
436
   * @param qformat, the format of document user want to get
437
   */
438
  public boolean handleReadAction(String docid, String qformat)
439
  {
440
    Properties prop = new Properties();
441
    String message ="";
442
    prop.put("action", "read");
443
    prop.put("qformat", qformat);
444
    prop.put("docid", docid);
445
    
446
    message = getMetacatString(prop);
447
    message = message.trim();
448
    //MetaCatUtil.debugMessage("Read Message: "+message, 30);
449
    if (message==null || message.equals("")||message.indexOf("<error>") != -1 )
450
    {//there was an error
451
      
452
      return false;
453
    }
454
    else
455
    {//successfully
456
      return true;
457
    } 
458
    
459
  }
460
  
461
  
462
  /**
463
   * Method to hanld inset or update xml document
464
   *
465
   * @param xmlDocument, the content of xml qformat
466
   * @param docid, the docid of the document
467
   * @param action, insert or update
468
   */
469
  public boolean handleXMLDocument(String xmlDocument, String docid, 
470
                                                              String action)
471
 
472
  { //-attempt to write file to metacat
473
    String access = "no";
474
    StringBuffer fileText = new StringBuffer();
475
    StringBuffer messageBuf = new StringBuffer();
476
    String accessFileId = null;
477
    Properties prop = new Properties();
478
    prop.put("action", action);
479
    prop.put("public", access);  //This is the old way of controlling access
480
    prop.put("doctext", xmlDocument);
481
    prop.put("docid", docid);
482
    
483
    String message = getMetacatString(prop);
484
    logMetacat.info("Insert or Update Message: "+message);
485
    if(message.indexOf("<error>") != -1)
486
    {//there was an error
487
      
488
      return false;
489
    }
490
    else if(message.indexOf("<success>") != -1)
491
    {//the operation worked
492
     //write the file to the cache and return the file object
493
     return true;
494
       
495
    }
496
    else
497
    {//something weird happened.
498
      return false;
499
    } 
500
   
501
   
502
  }
503
  
504
   public boolean handleDeleteFile(String name)
505
  {
506
    
507
    Properties prop = new Properties();
508
    prop.put("action", "delete");
509
    prop.put("docid", name);
510
 
511
    String message = getMetacatString(prop);
512
    logMetacat.info("Delete Message: "+message);
513
    if(message.indexOf("<error>") != -1)
514
    {//there was an error
515
      
516
      return false;
517
    }
518
    else if(message.indexOf("<success>") != -1)
519
    {//the operation worked
520
     //write the file to the cache and return the file object
521
     return true;
522
       
523
    }
524
    else
525
    {//something weird happened.
526
      return false;
527
    } 
528
  }
529
  
530
  
531
  /**
532
   * sends a data file to the metacat using "multipart/form-data" encoding
533
   *
534
   * @param id the id to assign to the file on metacat (e.g., knb.1.1)
535
   * @param file the file to send
536
   */
537
  public boolean insertDataFile(String id, File file)
538
  {
539
    String response = null;
540
    //Get response for calling sendDataFile function
541
    response = sendDataFile(id, file);
542
    
543
    if (response.indexOf("success") != -1)
544
    {
545
      //insert successfully
546
      return true;
547
    }
548
    else
549
    {
550
      return false;
551
    }
552
  }
553
  
554
  /**
555
   * sends a data file to the metacat using "multipart/form-data" encoding
556
   *
557
   * @param id the id to assign to the file on metacat (e.g., knb.1.1)
558
   * @param file the file to send
559
   */
560
  public String sendDataFile(String id, File file) 
561
  {
562
    String response = "";
563
    InputStream returnStream = null;
144
	/**
145
	 * Run an initial test that always passes to check that the test
146
	 * harness is working.
147
	 */
148
	public void initialize() {
149
		assertTrue(1 == 1);
150
	}
564 151

  
565
    // Now contact metacat and send the request
566
    try
567
    {
568
      //FileInputStream data = new FileInputStream(file);
569
      System.setProperty("java.protocol.handler.pkgs","HTTPClient");
570
      URL url = new URL(metacatURL);
571
      edu.ucsb.nceas.morpho.framework.HttpMessage msg = 
572
                        new edu.ucsb.nceas.morpho.framework.HttpMessage(url);
573
      Properties args = new Properties();
574
      args.put("action", "upload");
575
      args.put("docid", id);
152
	/**
153
	 * Test the login to neceas succesfully
154
	 */
155
	public void testNCEASLogin() {
156
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
157
		String passwd = "123456";
158
		assertTrue(logIn(user, passwd));
159
		//assertTrue( withProtocol.getProtocol().equals("http"));
160
	}
576 161

  
577
      Properties dataStreams = new Properties();
578
      String filename = file.getAbsolutePath();
579
      System.out.println("the absolute path is "+filename);
580
      dataStreams.put("datafile", filename);
581
       
582
  
583
    
584
      returnStream = msg.sendPostData(args, dataStreams);
585
        
586
      InputStreamReader returnStreamReader = 
587
                        new InputStreamReader(returnStream);
588
      StringWriter sw = new StringWriter();
589
      int len;
590
      char[] characters = new char[512];
591
      while ((len = returnStreamReader.read(characters, 0, 512)) != -1)
592
      {
593
        sw.write(characters, 0, len);
594
      }
595
      returnStreamReader.close();
596
      response = sw.toString();
597
      sw.close();
598
   
599
    } 
600
    catch(Exception e) 
601
    {
602
      e.printStackTrace(System.err);
603
    }
604
    return response;
605
  }
606
  
607
  public String getMetacatString(Properties prop)
608
  {
609
    String response = null;
162
	/**
163
	 * Test the login to neceas failed
164
	 */
165
	public void testNCEASLoginFail() {
166
		String user = "uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
167
		String passwd = "12345678";
168
		assertTrue(!logIn(user, passwd));
610 169

  
611
    // Now contact metacat and send the request
612
    try
613
    {
614
      InputStreamReader returnStream = 
615
                        new InputStreamReader(getMetacatInputStream(prop));
616
      StringWriter sw = new StringWriter();
617
      int len;
618
      char[] characters = new char[512];
619
      while ((len = returnStream.read(characters, 0, 512)) != -1)
620
      {
621
        sw.write(characters, 0, len);
622
      }
623
      returnStream.close();
624
      response = sw.toString();
625
      sw.close();
626
    }
627
    catch(Exception e)
628
    {
629
      return null;
630
    }
631
  
632
    return response;
633
  }
634
  
635
   /**
636
   * Send a request to Metacat
637
   *
638
   * @param prop the properties to be sent to Metacat
639
   * @return InputStream as returned by Metacat
640
   */
641
  public InputStream getMetacatInputStream(Properties prop)
642
  {
643
    InputStream returnStream = null;
644
    // Now contact metacat and send the request
645
    try
646
    {
647
     
648
      URL url = new URL(metacatURL);
649
      edu.ucsb.nceas.morpho.framework.HttpMessage msg = 
650
              new edu.ucsb.nceas.morpho.framework.HttpMessage(url);
651
      returnStream = msg.sendPostMessage(prop);
652
      return returnStream;
653
    }
654
    catch(Exception e)
655
    {
656
      e.printStackTrace(System.err);
657
     
658
    }
659
    return returnStream;
660
   
661
  }
170
	}
662 171

  
663
 
172
	/**
173
	 * Test the login to lter failed
174
	 */
175
	public void testLterReferralLoginFail() {
176
		String user = "uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
177
		String passwd = "qVyGpveb";
178
		assertTrue(!logIn(user, passwd));
179
		//assertTrue( withProtocol.getProtocol().equals("http"));
180
	}
664 181

  
182
	/**
183
	 * Test insert a xml document successfully
184
	 */
185
	public void testInsertXMLDocument() throws PropertyNotFoundException {
186
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
187
				+ PropertyService.getProperty("accNumSeparator") + "1";
188
		logMetacat.info("insert docid: " + name);
189
		String content = "<?xml version=\"1.0\"?>"
190
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
191
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
192
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
193
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
194
				+ "</identifier>" + "<allow>"
195
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
196
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
197
				+ "<principal>public</principal>" + "<permission>read</permission>"
198
				+ "</allow>" + "</acl>";
199
		logMetacat.info("xml document: " + content);
200
		assertTrue(handleXMLDocument(content, name, "insert"));
201

  
202
	}
203

  
204
	/**
205
	 * Test insert a invalidate xml document successfully
206
	 * In the String, there is no <!Doctype ... Public/System/>
207
	 */
208
	public void testInsertInvalidateXMLDocument() throws PropertyNotFoundException  {
209
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
210
				+ PropertyService.getProperty("accNumSeparator") + "1";
211
		logMetacat.info("insert docid: " + name);
212
		String content = "<?xml version=\"1.0\"?>"
213
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
214
				+ "</identifier>" + "<allow>"
215
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
216
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
217
				+ "<principal>public</principal>" + "<permission>read</permission>"
218
				+ "</allow>" + "</acl>";
219
		logMetacat.info("xml document: " + content);
220
		assertTrue(handleXMLDocument(content, name, "insert"));
221
	}
222

  
223
	/**
224
	 * Test insert a non well-formed xml document successfully
225
	 * There is no </acl> in this string
226
	 */
227
	public void testInsertNonWellFormedXMLDocument() throws PropertyNotFoundException  {
228
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
229
				+ PropertyService.getProperty("accNumSeparator") + "1";
230
		logMetacat.info("insert non well-formed docid: " + name);
231
		String content = "<?xml version=\"1.0\"?>"
232
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
233
				+ "</identifier>" + "<allow>"
234
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
235
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
236
				+ "<principal>public</principal>" + "<permission>read</permission>"
237
				+ "</allow>";
238

  
239
		logMetacat.info("xml document: " + content);
240
		assertTrue(!handleXMLDocument(content, name, "insert"));
241
	}
242

  
243
	/**
244
	 * Test read a xml document  in xml format successfully
245
	 */
246
	public void testReadXMLDocumentXMLFormat() throws PropertyNotFoundException  {
247
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
248
				+ PropertyService.getProperty("accNumSeparator") + "1";
249
		assertTrue(handleReadAction(name, "xml"));
250

  
251
	}
252

  
253
	/**
254
	 * Test read a xml document  in html format successfully
255
	 */
256
	public void testReadXMLDocumentHTMLFormat() throws PropertyNotFoundException {
257
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
258
				+ PropertyService.getProperty("accNumSeparator") + "1";
259
		assertTrue(handleReadAction(name, "html"));
260

  
261
	}
262

  
263
	/**
264
	 * Test read a xml document  in zip format successfully
265
	 */
266
	public void testReadXMLDocumentZipFormat() throws PropertyNotFoundException {
267
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
268
				+ PropertyService.getProperty("accNumSeparator") + "1";
269
		assertTrue(handleReadAction(name, "zip"));
270

  
271
	}
272

  
273
	/**
274
	 * Test insert a xml document successfully
275
	 */
276
	public void testUpdateXMLDocument() throws PropertyNotFoundException {
277
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
278
				+ PropertyService.getProperty("accNumSeparator") + "2";
279
		logMetacat.info("update docid: " + name);
280
		String content = "<?xml version=\"1.0\"?>"
281
				+ "<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
282
				+ "eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
283
				+ "edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
284
				+ "<acl authSystem=\"knb\" order=\"allowFirst\">" + "<identifier>" + name
285
				+ "</identifier>" + "<allow>"
286
				+ "<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
287
				+ "<permission>all</permission>" + "</allow>" + "<allow>"
288
				+ "<principal>public</principal>" + "<permission>read</permission>"
289
				+ "</allow>" + "</acl>";
290
		logMetacat.info("xml document: " + content);
291
		assertTrue(handleXMLDocument(content, name, "update"));
292

  
293
	}
294

  
295
	/**
296
	 * Test insert a data file successfully
297
	 */
298
	public void testInertDataFile() throws PropertyNotFoundException {
299
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
300
				+ PropertyService.getProperty("accNumSeparator") + "1";
301
		logMetacat.info("insert data file docid: " + name);
302
		logMetacat.info("insert data file ");
303
		File hello = new File("test/jones.204.22.xml");
304

  
305
		assertTrue(insertDataFile(name, hello));
306
	}
307

  
308
	/**
309
	 * Test delete a xml document successfully
310
	 */
311
	public void testDeleteXMLDocument() throws PropertyNotFoundException {
312
		String name = "john" + PropertyService.getProperty("accNumSeparator") + serialNumber
313
				+ PropertyService.getProperty("accNumSeparator") + "2";
314
		logMetacat.info("delete docid: " + name);
315
		assertTrue(handleDeleteFile(name));
316

  
317
	}
318

  
319
	/**
320
	 * Test logout action
321
	 */
322
	public void testLogOut() {
323

  
324
		assertTrue(handleLogOut());
325

  
326
	}
327

  
328
	/**
329
	 * Method to hanld login action
330
	 *
331
	 * @param usrerName, the DN name of the test method
332
	 * @param passWord, the passwd of the user
333
	 */
334

  
335
	public boolean logIn(String userName, String passWord) {
336
		Properties prop = new Properties();
337
		prop.put("action", "login");
338
		prop.put("qformat", "xml");
339
		prop.put("username", userName);
340
		prop.put("password", passWord);
341

  
342
		// Now contact metacat
343
		String response = getMetacatString(prop);
344
		logMetacat.info("Login Message: " + response);
345
		boolean connected = false;
346
		if (response.indexOf("<login>") != -1) {
347
			connected = true;
348
		} else {
349

  
350
			connected = false;
351
		}
352

  
353
		return connected;
354
	}
355

  
356
	/**
357
	 * Method to hanld logout action
358
	 *
359
	 * @param usrerName, the DN name of the test method
360
	 * @param passWord, the passwd of the user
361
	 */
362

  
363
	public boolean handleLogOut() {
364
		boolean disConnected = false;
365
		Properties prop = new Properties();
366
		prop.put("action", "logout");
367
		prop.put("qformat", "xml");
368

  
369
		String response = getMetacatString(prop);
370
		logMetacat.info("Logout Message: " + response);
371
		edu.ucsb.nceas.morpho.framework.HttpMessage.setCookie(null);
372

  
373
		if (response.indexOf("<logout>") != -1) {
374
			disConnected = true;
375
		} else {
376
			disConnected = false;
377
		}
378

  
379
		return disConnected;
380
	}
381

  
382
	/**
383
	 * Method to hanld read both xml and data file
384
	 *
385
	 * @param docid, the docid of the document want to read
386
	 * @param qformat, the format of document user want to get
387
	 */
388
	public boolean handleReadAction(String docid, String qformat) {
389
		Properties prop = new Properties();
390
		String message = "";
391
		prop.put("action", "read");
392
		prop.put("qformat", qformat);
393
		prop.put("docid", docid);
394

  
395
		message = getMetacatString(prop);
396
		message = message.trim();
397
		//MetaCatUtil.debugMessage("Read Message: "+message, 30);
398
		if (message == null || message.equals("") || message.indexOf("<error>") != -1) {//there was an error
399

  
400
			return false;
401
		} else {//successfully
402
			return true;
403
		}
404

  
405
	}
406

  
407
	/**
408
	 * Method to hanld inset or update xml document
409
	 *
410
	 * @param xmlDocument, the content of xml qformat
411
	 * @param docid, the docid of the document
412
	 * @param action, insert or update
413
	 */
414
	public boolean handleXMLDocument(String xmlDocument, String docid, String action)
415

  
416
	{ //-attempt to write file to metacat
417
		String access = "no";
418
		StringBuffer fileText = new StringBuffer();
419
		StringBuffer messageBuf = new StringBuffer();
420
		String accessFileId = null;
421
		Properties prop = new Properties();
422
		prop.put("action", action);
423
		prop.put("public", access); //This is the old way of controlling access
424
		prop.put("doctext", xmlDocument);
425
		prop.put("docid", docid);
426

  
427
		String message = getMetacatString(prop);
428
		logMetacat.info("Insert or Update Message: " + message);
429
		if (message.indexOf("<error>") != -1) {//there was an error
430

  
431
			return false;
432
		} else if (message.indexOf("<success>") != -1) {//the operation worked
433
			//write the file to the cache and return the file object
434
			return true;
435

  
436
		} else {//something weird happened.
437
			return false;
438
		}
439

  
440
	}
441

  
442
	public boolean handleDeleteFile(String name) {
443

  
444
		Properties prop = new Properties();
445
		prop.put("action", "delete");
446
		prop.put("docid", name);
447

  
448
		String message = getMetacatString(prop);
449
		logMetacat.info("Delete Message: " + message);
450
		if (message.indexOf("<error>") != -1) {//there was an error
451

  
452
			return false;
453
		} else if (message.indexOf("<success>") != -1) {//the operation worked
454
			//write the file to the cache and return the file object
455
			return true;
456

  
457
		} else {//something weird happened.
458
			return false;
459
		}
460
	}
461

  
462
	/**
463
	 * sends a data file to the metacat using "multipart/form-data" encoding
464
	 *
465
	 * @param id the id to assign to the file on metacat (e.g., knb.1.1)
466
	 * @param file the file to send
467
	 */
468
	public boolean insertDataFile(String id, File file) {
469
		String response = null;
470
		//Get response for calling sendDataFile function
471
		response = sendDataFile(id, file);
472

  
473
		if (response.indexOf("success") != -1) {
474
			//insert successfully
475
			return true;
476
		} else {
477
			return false;
478
		}
479
	}
480

  
481
	/**
482
	 * sends a data file to the metacat using "multipart/form-data" encoding
483
	 *
484
	 * @param id the id to assign to the file on metacat (e.g., knb.1.1)
485
	 * @param file the file to send
486
	 */
487
	public String sendDataFile(String id, File file) {
488
		String response = "";
489
		InputStream returnStream = null;
490

  
491
		// Now contact metacat and send the request
492
		try {
493
			//FileInputStream data = new FileInputStream(file);
494
			System.setProperty("java.protocol.handler.pkgs", "HTTPClient");
495
			URL url = new URL(metacatURL);
496
			edu.ucsb.nceas.morpho.framework.HttpMessage msg = new edu.ucsb.nceas.morpho.framework.HttpMessage(
497
					url);
498
			Properties args = new Properties();
499
			args.put("action", "upload");
500
			args.put("docid", id);
501

  
502
			Properties dataStreams = new Properties();
503
			String filename = file.getAbsolutePath();
504
			System.out.println("the absolute path is " + filename);
505
			dataStreams.put("datafile", filename);
506

  
507
			returnStream = msg.sendPostData(args, dataStreams);
508

  
509
			InputStreamReader returnStreamReader = new InputStreamReader(returnStream);
510
			StringWriter sw = new StringWriter();
511
			int len;
512
			char[] characters = new char[512];
513
			while ((len = returnStreamReader.read(characters, 0, 512)) != -1) {
514
				sw.write(characters, 0, len);
515
			}
516
			returnStreamReader.close();
517
			response = sw.toString();
518
			sw.close();
519

  
520
		} catch (Exception e) {
521
			e.printStackTrace(System.err);
522
		}
523
		return response;
524
	}
525

  
526
	public String getMetacatString(Properties prop) {
527
		String response = null;
528

  
529
		// Now contact metacat and send the request
530
		try {
531
			InputStreamReader returnStream = new InputStreamReader(
532
					getMetacatInputStream(prop));
533
			StringWriter sw = new StringWriter();
534
			int len;
535
			char[] characters = new char[512];
536
			while ((len = returnStream.read(characters, 0, 512)) != -1) {
537
				sw.write(characters, 0, len);
538
			}
539
			returnStream.close();
540
			response = sw.toString();
541
			sw.close();
542
		} catch (Exception e) {
543
			return null;
544
		}
545

  
546
		return response;
547
	}
548

  
549
	/**
550
	 * Send a request to Metacat
551
	 *
552
	 * @param prop the properties to be sent to Metacat
553
	 * @return InputStream as returned by Metacat
554
	 */
555
	public InputStream getMetacatInputStream(Properties prop) {
556
		InputStream returnStream = null;
557
		// Now contact metacat and send the request
558
		try {
559

  
560
			URL url = new URL(metacatURL);
561
			edu.ucsb.nceas.morpho.framework.HttpMessage msg = new edu.ucsb.nceas.morpho.framework.HttpMessage(
562
					url);
563
			returnStream = msg.sendPostMessage(prop);
564
			return returnStream;
565
		} catch (Exception e) {
566
			e.printStackTrace(System.err);
567

  
568
		}
569
		return returnStream;
570

  
571
	}
572

  
665 573
}

Also available in: Unified diff