Project

General

Profile

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

    
27
package edu.ucsb.nceas.metacatnettest;
28

    
29
import edu.ucsb.nceas.metacat.*;
30
import edu.ucsb.nceas.utilities.Options;
31
import edu.ucsb.nceas.morpho.framework.*;
32
import junit.framework.Test;
33
import junit.framework.TestCase;
34
import junit.framework.TestResult;
35
import junit.framework.TestSuite;
36

    
37
import java.io.*;
38
import java.net.*;
39
import java.util.*;
40

    
41
import org.apache.log4j.Logger;
42

    
43

    
44
/**
45
 * A JUnit test for testing Step class processing
46
 */
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
  }
73

    
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
 }
91

    
92
  /**
93
   * Release any objects after tests are complete
94
   */
95
  public void tearDown()
96
  {
97
  }
98

    
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("testLterReferralLogin"));
111
    suite.addTest(new MetaCatServletNetTest("testLterReferralLoginFail"));
112
    suite.addTest(new MetaCatServletNetTest("testPiscoReferralLogin"));
113
    suite.addTest(new MetaCatServletNetTest("testPiscoReferralLoginFail"));
114
    suite.addTest(new MetaCatServletNetTest("testNCEASLoginFail"));
115
    //Should put a login successfully at the end of login test
116
    //So insert or update can have cookie.
117
    suite.addTest(new MetaCatServletNetTest("testNCEASLogin"));
118
    
119
    //create random number for docid, so it can void repeat
120
    number = Math.random()*100000;
121
    serial = Integer.toString(((new Double(number)).intValue()));
122
    logMetacat.info("serial: "+serial);
123
    suite.addTest(new MetaCatServletNetTest("testInsertXMLDocument", serial));
124
    suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentXMLFormat", 
125
                                                        serial));
126
    suite.addTest(new MetaCatServletNetTest("testUpdateXMLDocument",serial));    
127
    suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentHTMLFormat", 
128
                                                        serial));
129
    suite.addTest(new MetaCatServletNetTest("testReadXMLDocumentZipFormat", 
130
                                                        serial));
131
    
132
    suite.addTest(new MetaCatServletNetTest("testDeleteXMLDocument",serial));
133
    
134
    //insert invalid xml document
135
    number = Math.random()*100000;
136
    serial = Integer.toString(((new Double(number)).intValue()));
137
    suite.addTest(new MetaCatServletNetTest("testInsertInvalidateXMLDocument",
138
                                                                  serial));    
139
    //insert non well formed document
140
    number = Math.random()*100000;
141
    serial = Integer.toString(((new Double(number)).intValue())); 
142
   suite.addTest(new MetaCatServletNetTest("testInsertNonWellFormedXMLDocument",
143
                                                            serial));
144
    //insert data file  
145
    number = Math.random()*100000;
146
    serial = Integer.toString(((new Double(number)).intValue()));
147
    suite.addTest(new MetaCatServletNetTest("testInertDataFile", serial));
148
    
149
    suite.addTest(new MetaCatServletNetTest("testLogOut"));                   
150
                              
151
    return suite;
152
  }
153
  
154

    
155

    
156
  /**
157
   * Run an initial test that always passes to check that the test
158
   * harness is working.
159
   */
160
  public void initialize()
161
  {
162
    assertTrue(1 == 1);
163
  }
164

    
165
  /**
166
   * Test the login to neceas succesfully
167
   */
168
  public void testNCEASLogin()
169
  {
170
    String user="uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
171
    String passwd="123456";
172
    assertTrue(logIn(user,passwd));
173
    //assertTrue( withProtocol.getProtocol().equals("http"));
174
  }
175
  
176
  /**
177
   * Test the login to neceas failed
178
   */
179
  public void testNCEASLoginFail()
180
  {
181
    String user="uid=john,o=NCEAS,dc=ecoinformatics,dc=org";
182
    String passwd="12345678";
183
    assertTrue(!logIn(user,passwd));
184
    
185
  }
186
  
187
  /**
188
   * Test the login to lter succesfully
189
   */
190
  public void testLterReferralLogin()
191
  {
192
    String user="uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
193
    String passwd="qVyGpVeb";
194
    assertTrue(logIn(user,passwd));
195
    
196
  }
197
  
198
  /**
199
   * Test the login to lter failed
200
   */
201
  public void testLterReferralLoginFail()
202
  {
203
    String user="uid=jtao,o=LTER,dc=ecoinformatics,dc=org";
204
    String passwd="qVyGpveb";
205
    assertTrue(!logIn(user,passwd));
206
    //assertTrue( withProtocol.getProtocol().equals("http"));
207
  }
208
  
209
 /**
210
   * Test the login to pisco succesfully
211
   */
212
   public void testPiscoReferralLogin()
213
  {
214
    String user="uid=tao,o=PISCO,dc=ecoinformatics,dc=org";
215
    String passwd="purple";
216
    assertTrue(logIn(user,passwd));
217
    //assertTrue( withProtocol.getProtocol().equals("http"));
218
  }
219
  
220
 /**
221
   * Test the login to pisco failed
222
   */
223
  public void testPiscoReferralLoginFail()
224
  {
225
    String user="uid=tao,o=PISCO,dc=ecoinformatics,dc=org";
226
    String passwd="hello";
227
    assertTrue(!logIn(user,passwd));
228
    //assertTrue( withProtocol.getProtocol().equals("http"));
229
  }
230
  
231
 /**
232
   * Test insert a xml document successfully
233
   */
234
  public void testInsertXMLDocument()
235
  {
236
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
237
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
238
    logMetacat.info("insert docid: "+name);
239
    String content="<?xml version=\"1.0\"?>"
240
                   +"<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
241
                   +"eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
242
                   +"edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
243
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
244
                   +"<identifier>"+name+"</identifier>"
245
                   +"<allow>"
246
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
247
                   +"<permission>all</permission>"
248
                   +"</allow>"
249
                   +"<allow>"
250
                   +"<principal>public</principal>"
251
                   +"<permission>read</permission>"
252
                   +"</allow>"
253
                   +"</acl>";
254
    logMetacat.info("xml document: "+content);
255
     assertTrue(handleXMLDocument(content, name, "insert"));
256
   
257
  }
258
  
259
  /**
260
   * Test insert a invalidate xml document successfully
261
   * In the String, there is no <!Doctype ... Public/System/>
262
   */
263
  public void testInsertInvalidateXMLDocument()
264
  {
265
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
266
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
267
    logMetacat.info("insert docid: "+name);
268
    String content="<?xml version=\"1.0\"?>"
269
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
270
                   +"<identifier>"+name+"</identifier>"
271
                   +"<allow>"
272
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
273
                   +"<permission>all</permission>"
274
                   +"</allow>"
275
                   +"<allow>"
276
                   +"<principal>public</principal>"
277
                   +"<permission>read</permission>"
278
                   +"</allow>"
279
                   +"</acl>";
280
    logMetacat.info("xml document: "+content);
281
     assertTrue(handleXMLDocument(content, name, "insert"));
282
  }
283
  
284
   /**
285
   * Test insert a non well-formed xml document successfully
286
   * There is no </acl> in this string
287
   */
288
  public void testInsertNonWellFormedXMLDocument()
289
  {
290
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
291
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
292
    logMetacat.info("insert non well-formed docid: "+name);
293
    String content="<?xml version=\"1.0\"?>"
294
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
295
                   +"<identifier>"+name+"</identifier>"
296
                   +"<allow>"
297
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
298
                   +"<permission>all</permission>"
299
                   +"</allow>"
300
                   +"<allow>"
301
                   +"<principal>public</principal>"
302
                   +"<permission>read</permission>"
303
                   +"</allow>";
304
  
305
     logMetacat.info("xml document: "+content);
306
     assertTrue(!handleXMLDocument(content, name, "insert"));
307
  } 
308

    
309
  /**
310
   * Test read a xml document  in xml format successfully
311
   */
312
  public void testReadXMLDocumentXMLFormat()
313
  {
314
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
315
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
316
    assertTrue(handleReadAction(name, "xml"));
317
   
318
  } 
319

    
320
  /**
321
   * Test read a xml document  in html format successfully
322
   */
323
  public void testReadXMLDocumentHTMLFormat()
324
  {
325
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
326
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
327
    assertTrue(handleReadAction(name, "html"));
328
   
329
  }
330

    
331
 
332
  /**
333
   * Test read a xml document  in zip format successfully
334
   */
335
  public void testReadXMLDocumentZipFormat()
336
  {
337
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
338
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
339
    assertTrue(handleReadAction(name, "zip"));
340
   
341
  }
342
  
343
  /**
344
   * Test insert a xml document successfully
345
   */
346
  public void testUpdateXMLDocument()
347
  {
348
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
349
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"2";
350
    logMetacat.info("update docid: "+name);
351
    String content="<?xml version=\"1.0\"?>"
352
                   +"<!DOCTYPE acl PUBLIC \"-//ecoinformatics.org//"
353
                   +"eml-access-2.0.0beta6//EN\" \"http://pine.nceas.ucsb."
354
                   +"edu:8080/tao/dtd/eml-access-2.0.0beta6.dtd\">"
355
                   +"<acl authSystem=\"knb\" order=\"allowFirst\">"
356
                   +"<identifier>"+name+"</identifier>"
357
                   +"<allow>"
358
             +"<principal>uid=john,o=NCEAS,dc=ecoinformatics,dc=org</principal>"
359
                   +"<permission>all</permission>"
360
                   +"</allow>"
361
                   +"<allow>"
362
                   +"<principal>public</principal>"
363
                   +"<permission>read</permission>"
364
                   +"</allow>"
365
                   +"</acl>";
366
     logMetacat.info("xml document: "+content);
367
     assertTrue(handleXMLDocument(content, name, "update"));
368
   
369
  }
370
  
371
  /**
372
   * Test insert a data file successfully
373
   */
374
  public void testInertDataFile()
375
  {
376
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
377
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"1";
378
    logMetacat.info("insert data file docid: "+name);
379
    logMetacat.info("insert data file ");
380
    File hello = new File("test/edu/ucsb/nceas/metacatnettest/hello.txt");
381
   
382
    assertTrue(insertDataFile(name, hello));
383
  }
384
  
385
  /**
386
   * Test delete a xml document successfully
387
   */
388
  public void testDeleteXMLDocument()
389
  {
390
    String name = "john"+MetaCatUtil.getOption("accNumSeparator")
391
                     +serialNumber+MetaCatUtil.getOption("accNumSeparator")+"2";
392
    logMetacat.info("delete docid: "+name);
393
    assertTrue(handleDeleteFile(name));
394
   
395
  }
396
  
397
  
398
       
399
  /**
400
   * Test logout action
401
   */
402
  public void testLogOut()
403
  {
404
    
405
    assertTrue(handleLogOut());
406
   
407
  }
408
  
409
 /**
410
   * Method to hanld login action
411
   *
412
   * @param usrerName, the DN name of the test method
413
   * @param passWord, the passwd of the user
414
   */
415
  
416
  public boolean logIn(String userName, String passWord)
417
  {
418
    Properties prop = new Properties();
419
    prop.put("action", "login");
420
    prop.put("qformat", "xml");
421
    prop.put("username", userName);
422
    prop.put("password", passWord);
423

    
424
    // Now contact metacat
425
    String response = getMetacatString(prop);
426
    logMetacat.info("Login Message: "+response);
427
    boolean connected = false;
428
    if (response.indexOf("<login>") != -1) {
429
      connected = true;
430
    } else {
431
      
432
      connected = false;
433
    }
434

    
435
    return connected;
436
  }
437
  
438
  /**
439
   * Method to hanld logout action
440
   *
441
   * @param usrerName, the DN name of the test method
442
   * @param passWord, the passwd of the user
443
   */
444
  
445
  public boolean handleLogOut()
446
  {
447
    boolean disConnected =false;
448
    Properties prop = new Properties();
449
    prop.put("action", "logout");
450
    prop.put("qformat", "xml");
451
  
452
    String response = getMetacatString(prop);
453
    logMetacat.info("Logout Message: "+response);
454
    edu.ucsb.nceas.morpho.framework.HttpMessage.setCookie(null);
455
     
456
    if (response.indexOf("<logout>") != -1) 
457
    {
458
      disConnected = true;
459
    } 
460
    else 
461
    {
462
      disConnected = false;
463
    }
464

    
465
    return disConnected;
466
  }
467
  
468
  /**
469
   * Method to hanld read both xml and data file
470
   *
471
   * @param docid, the docid of the document want to read
472
   * @param qformat, the format of document user want to get
473
   */
474
  public boolean handleReadAction(String docid, String qformat)
475
  {
476
    Properties prop = new Properties();
477
    String message ="";
478
    prop.put("action", "read");
479
    prop.put("qformat", qformat);
480
    prop.put("docid", docid);
481
    
482
    message = getMetacatString(prop);
483
    message = message.trim();
484
    //MetaCatUtil.debugMessage("Read Message: "+message, 30);
485
    if (message==null || message.equals("")||message.indexOf("<error>") != -1 )
486
    {//there was an error
487
      
488
      return false;
489
    }
490
    else
491
    {//successfully
492
      return true;
493
    } 
494
    
495
  }
496
  
497
  
498
  /**
499
   * Method to hanld inset or update xml document
500
   *
501
   * @param xmlDocument, the content of xml qformat
502
   * @param docid, the docid of the document
503
   * @param action, insert or update
504
   */
505
  public boolean handleXMLDocument(String xmlDocument, String docid, 
506
                                                              String action)
507
 
508
  { //-attempt to write file to metacat
509
    String access = "no";
510
    StringBuffer fileText = new StringBuffer();
511
    StringBuffer messageBuf = new StringBuffer();
512
    String accessFileId = null;
513
    Properties prop = new Properties();
514
    prop.put("action", action);
515
    prop.put("public", access);  //This is the old way of controlling access
516
    prop.put("doctext", xmlDocument);
517
    prop.put("docid", docid);
518
    
519
    String message = getMetacatString(prop);
520
    logMetacat.info("Insert or Update Message: "+message);
521
    if(message.indexOf("<error>") != -1)
522
    {//there was an error
523
      
524
      return false;
525
    }
526
    else if(message.indexOf("<success>") != -1)
527
    {//the operation worked
528
     //write the file to the cache and return the file object
529
     return true;
530
       
531
    }
532
    else
533
    {//something weird happened.
534
      return false;
535
    } 
536
   
537
   
538
  }
539
  
540
   public boolean handleDeleteFile(String name)
541
  {
542
    
543
    Properties prop = new Properties();
544
    prop.put("action", "delete");
545
    prop.put("docid", name);
546
 
547
    String message = getMetacatString(prop);
548
    logMetacat.info("Delete Message: "+message);
549
    if(message.indexOf("<error>") != -1)
550
    {//there was an error
551
      
552
      return false;
553
    }
554
    else if(message.indexOf("<success>") != -1)
555
    {//the operation worked
556
     //write the file to the cache and return the file object
557
     return true;
558
       
559
    }
560
    else
561
    {//something weird happened.
562
      return false;
563
    } 
564
  }
565
  
566
  
567
  /**
568
   * sends a data file to the metacat using "multipart/form-data" encoding
569
   *
570
   * @param id the id to assign to the file on metacat (e.g., knb.1.1)
571
   * @param file the file to send
572
   */
573
  public boolean insertDataFile(String id, File file)
574
  {
575
    String response = null;
576
    //Get response for calling sendDataFile function
577
    response = sendDataFile(id, file);
578
    
579
    if (response.indexOf("success") != -1)
580
    {
581
      //insert successfully
582
      return true;
583
    }
584
    else
585
    {
586
      return false;
587
    }
588
  }
589
  
590
  /**
591
   * sends a data file to the metacat using "multipart/form-data" encoding
592
   *
593
   * @param id the id to assign to the file on metacat (e.g., knb.1.1)
594
   * @param file the file to send
595
   */
596
  public String sendDataFile(String id, File file) 
597
  {
598
    String response = "";
599
    InputStream returnStream = null;
600

    
601
    // Now contact metacat and send the request
602
    try
603
    {
604
      //FileInputStream data = new FileInputStream(file);
605
      System.setProperty("java.protocol.handler.pkgs","HTTPClient");
606
      URL url = new URL(metacatURL);
607
      edu.ucsb.nceas.morpho.framework.HttpMessage msg = 
608
                        new edu.ucsb.nceas.morpho.framework.HttpMessage(url);
609
      Properties args = new Properties();
610
      args.put("action", "upload");
611
      args.put("docid", id);
612

    
613
      Properties dataStreams = new Properties();
614
      String filename = file.getAbsolutePath();
615
   
616
      dataStreams.put("datafile", filename);
617
       
618
  
619
    
620
      returnStream = msg.sendPostData(args, dataStreams);
621
        
622
      InputStreamReader returnStreamReader = 
623
                        new InputStreamReader(returnStream);
624
      StringWriter sw = new StringWriter();
625
      int len;
626
      char[] characters = new char[512];
627
      while ((len = returnStreamReader.read(characters, 0, 512)) != -1)
628
      {
629
        sw.write(characters, 0, len);
630
      }
631
      returnStreamReader.close();
632
      response = sw.toString();
633
      sw.close();
634
   
635
    } 
636
    catch(Exception e) 
637
    {
638
      e.printStackTrace(System.err);
639
    }
640
    return response;
641
  }
642
  
643
  public String getMetacatString(Properties prop)
644
  {
645
    String response = null;
646

    
647
    // Now contact metacat and send the request
648
    try
649
    {
650
      InputStreamReader returnStream = 
651
                        new InputStreamReader(getMetacatInputStream(prop));
652
      StringWriter sw = new StringWriter();
653
      int len;
654
      char[] characters = new char[512];
655
      while ((len = returnStream.read(characters, 0, 512)) != -1)
656
      {
657
        sw.write(characters, 0, len);
658
      }
659
      returnStream.close();
660
      response = sw.toString();
661
      sw.close();
662
    }
663
    catch(Exception e)
664
    {
665
      return null;
666
    }
667
  
668
    return response;
669
  }
670
  
671
   /**
672
   * Send a request to Metacat
673
   *
674
   * @param prop the properties to be sent to Metacat
675
   * @return InputStream as returned by Metacat
676
   */
677
  public InputStream getMetacatInputStream(Properties prop)
678
  {
679
    InputStream returnStream = null;
680
    // Now contact metacat and send the request
681
    try
682
    {
683
     
684
      URL url = new URL(metacatURL);
685
      edu.ucsb.nceas.morpho.framework.HttpMessage msg = 
686
              new edu.ucsb.nceas.morpho.framework.HttpMessage(url);
687
      returnStream = msg.sendPostMessage(prop);
688
      return returnStream;
689
    }
690
    catch(Exception e)
691
    {
692
      e.printStackTrace(System.err);
693
     
694
    }
695
    return returnStream;
696
   
697
  }
698

    
699
 
700

    
701
}
(1-1/2)