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-11-02 17:02:46 -0700 (Fri, 02 Nov 2007) $'
10
 * '$Revision: 3562 $'
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("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
  
148

    
149

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

    
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
  
181

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

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

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

    
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);
387

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

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

    
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;
564

    
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);
576

    
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;
610

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

    
663
 
664

    
665
}
(1-1/2)