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
 *
6
 *   '$Author: Serhan AKIN $'
7
 *     '$Date: 2009-07-15 10:54:27 +0300  $'
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 2 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22
 */
23
package edu.ucsb.nceas.metacattest.restservice;
24

    
25
import java.io.FileReader;
26
import java.io.IOException;
27
import java.io.Reader;
28
import java.util.Calendar;
29
import java.util.Date;
30
import java.util.GregorianCalendar;
31
import java.util.SimpleTimeZone;
32
import java.util.TimeZone;
33
import java.util.Vector;
34

    
35
import junit.framework.Test;
36
import junit.framework.TestSuite;
37
import edu.ucsb.nceas.MCTestCase;
38
import edu.ucsb.nceas.metacat.client.DocumentNotFoundException;
39
import edu.ucsb.nceas.metacat.client.MetacatAuthException;
40
import edu.ucsb.nceas.metacat.client.MetacatException;
41
import edu.ucsb.nceas.metacat.client.MetacatInaccessibleException;
42
import edu.ucsb.nceas.metacat.client.rest.MetacatRest;
43
import edu.ucsb.nceas.metacat.client.rest.MetacatRestClient;
44
import edu.ucsb.nceas.metacat.properties.PropertyService;
45
import edu.ucsb.nceas.utilities.IOUtil;
46
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
47

    
48
/**
49
 * A JUnit test for testing Step class processing
50
 */
51
public class MetacatRestClientTest extends MCTestCase{
52
	protected static String contextUrl;
53
	static {
54
		try {
55
		    contextUrl = PropertyService.getProperty("test.contextUrl");
56
			username = PropertyService.getProperty("test.mcUser");
57
			password = PropertyService.getProperty("test.mcPassword");
58
			anotheruser = PropertyService.getProperty("test.mcAnotherUser");
59
			anotherpassword = PropertyService.getProperty("test.mcAnotherPassword");
60
		} catch (PropertyNotFoundException pnfe) {
61
			System.err.println("Could not get property in static block: " 
62
					+ pnfe.getMessage());
63
		}
64
	}
65
	
66
	
67
	
68
    private String failpass = "sdfsdfsdfsd";
69
    private String prefix = "test";
70
    private String newdocid = null;
71
    private String testfile = "test/jones.204.22.xml";
72
    private String onlinetestdatafile = "test/onlineDataFile1";
73
    private String queryFile = "test/query.xml";
74
    private String testdocument = "";
75
    private MetacatRest m;
76
    private String spatialTestFile = "test/spatialEml.xml";
77
    private static final int TIME = 30;
78
    private static final String DOCID = "docid";
79
    private static final String DATAID = "dataid";
80
    
81
    private static final String public_doc_id = "serhan.3.1";
82
    private static final String authorized_doc_id = "serhan.4.2";
83
    private static final String notexisting_doc_id = "serhan.1.1";
84
    private static final String ecogridQueryFile= "test/restfiles/ecogrid_query.xml";
85

    
86

    
87
    private static final String insert_file = "test/restfiles/knb-lter-gce.109.6.xml";
88
    
89
    
90
    /**
91
     * Constructor to build the test
92
     *
93
     * @param name the name of the test method
94
     */
95
    public MetacatRestClientTest(String name)
96
    {
97
        super(name);
98
        newdocid = generateDocid();
99
    }
100

    
101
    /**
102
     * Establish a testing framework by initializing appropriate objects
103
     */
104
    public void setUp()
105
    {
106
        try {
107
            FileReader fr = new FileReader(testfile);
108
            testdocument = IOUtil.getAsString(fr, true);
109
        } catch (IOException ioe) {
110
            fail("Can't read test data to run the test: " + testfile);
111
        }
112

    
113
        m = new MetacatRestClient(contextUrl);
114
    }
115
    
116
    /**
117
     * Release any objects after tests are complete
118
     */
119
    public void tearDown()
120
    {
121
    }
122

    
123
    /**
124
     * Create a suite of tests to be run together
125
     */
126
    public static Test suite()
127
    {
128
      TestSuite suite = new TestSuite();
129
      suite.addTest(new MetacatRestClientTest("initialize"));
130
      suite.addTest(new MetacatRestClientTest("invalidLogin"));
131
      suite.addTest(new MetacatRestClientTest("login"));
132
      suite.addTest(new MetacatRestClientTest("logout"));
133
      suite.addTest(new MetacatRestClientTest("get"));
134
      suite.addTest(new MetacatRestClientTest("getPrivate"));
135
      suite.addTest(new MetacatRestClientTest("invalidGet"));
136
      suite.addTest(new MetacatRestClientTest("authenticatedGet"));
137
      suite.addTest(new MetacatRestClientTest("query"));
138
      suite.addTest(new MetacatRestClientTest("authenticatedQuery"));      
139
      suite.addTest(new MetacatRestClientTest("crud"));
140
      suite.addTest(new MetacatRestClientTest("getNextObject"));
141
      suite.addTest(new MetacatRestClientTest("getNextRevision"));
142
      suite.addTest(new MetacatRestClientTest("getAllDocids"));
143
      suite.addTest(new MetacatRestClientTest("isRegistered"));
144
      suite.addTest(new MetacatRestClientTest("addLSID"));
145
      return suite;
146
  }
147
    
148
    
149
    /**
150
     * Run an initial test that always passes to check that the test
151
     * harness is working.
152
     */
153
    public void initialize() {
154
        assertTrue(1 == 1);
155
    }
156
    
157
    /**
158
     * Test the login() function with valid credentials
159
     */
160
    public void login()
161
    {
162
        debug("\nStarting login test...");
163
        debug("-------------------------------------------------------");
164
        // Try a valid login
165
        try {
166
            String response = m.login(username, password);
167
            debug("login(): response=" + response);
168
            assertTrue(response != null);
169
            assertTrue(response.indexOf("<login>") != -1);
170
            String sessionId = m.getSessionId();
171
            debug("login(): Session ID=" + m.getSessionId());
172
            assertTrue(sessionId != null);
173
            assertTrue(response.indexOf(m.getSessionId()) != -1);
174
        } catch (MetacatAuthException mae) {
175
            fail("Authorization failed:\n" + mae.getMessage());
176
        } catch (MetacatInaccessibleException mie) {
177
            fail("Metacat Inaccessible:\n" + mie.getMessage());
178
        }
179
    }
180
    
181
    /**
182
     * Test the login() function with INVALID credentials
183
     */
184
    public void invalidLogin()
185
    {
186
        debug("\nStarting invalidLogin test...");
187
        debug("-------------------------------------------------------");
188
        // Try an invalid login
189
        String response = "";
190
        try {
191
        	response = m.login(username, failpass);        	
192
            fail("Authorization should have failed.");
193
        } catch (MetacatAuthException mae) {
194
        	debug("invalid login(): response=" + mae.getMessage());
195
            //assertTrue(1 == 1);
196
        } catch (MetacatInaccessibleException mie) {
197
            fail("Metacat Inaccessible:\n" + mie.getMessage());
198
        } 
199
    }
200
    
201
    /**
202
     * Test the logout() function. 
203
     */
204
    public void logout()
205
    {
206
       debug("\nStarting logout test...");
207
       debug("-------------------------------------------------------");
208
       try {
209
            m.login(username, password);
210
            String response = m.logout();
211
            debug("logout(): Response ="+response);
212
            assertTrue(response.indexOf("<success>") == -1);
213
        } catch (MetacatAuthException mae) {
214
            fail("Authorization failed:\n" + mae.getMessage());
215
        } catch (MetacatInaccessibleException mie) {
216
            fail("Metacat Inaccessible:\n" + mie.getMessage());
217
        } catch (MetacatException me) {
218
            if(me.getMessage().
219
              indexOf("Permission denied for user public inser") == -1){
220
               fail("Metacat Error:\n" + me.getMessage());
221
           }
222
        } catch (Exception e) {
223
            fail("General exception:\n" + e.getMessage());
224
        }
225
    }
226
    
227
    
228
    /**
229
     * Test the get() function with a public document
230
     */
231
    public void get()
232
    {
233
        debug("\nStarting get test...");
234
        debug("-------------------------------------------------------");        
235
        try {
236
            Reader r =  m.getObject(public_doc_id, null);            
237
            String doc = IOUtil.getAsString(r, true);
238
            doc = doc +"\n";
239
            debug("document:\n"+doc);
240
        } catch (MetacatInaccessibleException mie) {
241
            debug("Metacat Inaccessible:\n" + mie.getMessage());
242
        } catch (Exception e) {
243
        	e.printStackTrace();
244
            debug("General exception:\n" + e.getMessage());
245
        }
246
    }
247
    
248
    /**
249
     * Test the get() function with a private document
250
     */
251
    public void getPrivate()
252
    {
253
        debug("\nStarting getprivate  test...");
254
        debug("-------------------------------------------------------");        
255
        try {
256
            Reader r =  m.getObject(authorized_doc_id, null);            
257
            String doc = IOUtil.getAsString(r, true);
258
            doc = doc +"\n";
259
            debug("document:\n"+doc);
260
        } catch (MetacatInaccessibleException mie) {
261
            debug("Metacat Inaccessible:\n" + mie.getMessage());
262
        } catch (Exception e) {
263
            debug("General exception:\n" + e.getMessage());
264
        }
265
    }
266
    
267
    /**
268
     * Test the authenticatedGet() function with a private document without for a valid session
269
     */
270
    public void authenticatedGet()
271
    {
272
        debug("\nStarting authorizedGet test...");
273
        debug("-------------------------------------------------------");
274
        try {
275
        	m.login(username,password);
276
            Reader r =  m.authenticatedGetObject(authorized_doc_id, null);            
277
            String doc = IOUtil.getAsString(r, true);
278
            doc = doc +"\n";
279
            debug("document:\n"+doc);
280
        } catch (MetacatInaccessibleException mie) {
281
            debug("Metacat Inaccessible:\n" + mie.getMessage());
282
        } catch (Exception e) {
283
            debug("General exception:\n" + e.getMessage());
284
        }
285
    }
286
    
287
    /**
288
     * Test the get() function with a not existing document
289
     */
290
    public void invalidGet()
291
    {
292
        debug("\nStarting invalid get test ...");
293
        debug("-------------------------------------------------------");
294
        try {
295
            Reader r =  m.getObject(notexisting_doc_id, null);            
296
            String doc = IOUtil.getAsString(r, true);
297
            doc = doc +"\n";
298
            debug("document:\n"+doc);
299
        } catch (MetacatInaccessibleException mie) {
300
            debug("Metacat Inaccessible:\n" + mie.getMessage());
301
        } catch (DocumentNotFoundException doe) {
302
        	  debug("Document not found:\n" + doe.getMessage());
303
        } catch (Exception e) {
304
        	e.printStackTrace();
305
            debug("General exception:\n" + e.getMessage());
306
        }
307
    }
308
    
309
    /**
310
     * Test the query() function with a public session
311
     */
312
    public void query(){
313
    	debug("\nStarting query test ...");
314
        debug("-------------------------------------------------------");
315
    	try {
316
    	 FileReader fr = new FileReader(ecogridQueryFile);   	
317
    	 Reader r = m.query(fr);   
318
         String doc = IOUtil.getAsString(r, true);
319
         doc = doc +"\n";
320
         debug("document:\n"+doc);
321
         
322
        } catch (MetacatInaccessibleException mie) {
323
            fail("Metacat Inaccessible:\n" + mie.getMessage());
324
        } catch (Exception e) {
325
        	e.printStackTrace();
326
            fail("General exception:\n" + e.getMessage());
327
        }
328
    }
329
    
330
    
331
    
332
    /**
333
     * Test the authenticatedQuery() function
334
     */
335
    public void authenticatedQuery(){
336
    	debug("\nStarting authenticatedQuery test ...");
337
        debug("-------------------------------------------------------");
338
    	try {
339
    	 FileReader fr = new FileReader(ecogridQueryFile);	
340
    	 m.login(username,password);
341
    	 Reader r = m.authenticatedQuery(fr);   
342
         String doc = IOUtil.getAsString(r, true);
343
         doc = doc +"\n";
344
         debug("document:\n"+doc);
345
         
346
        } catch (MetacatAuthException mae) {
347
            fail("Authorization failed:\n" + mae.getMessage());
348
        } catch (MetacatInaccessibleException mie) {
349
            fail("Metacat Inaccessible:\n" + mie.getMessage());
350
        } catch (Exception e) {
351
        	e.printStackTrace();
352
            fail("General exception:\n" + e.getMessage());
353
        }
354
    }
355
    
356
    /**
357
     * Test the insert,update and delete function
358
     */
359
    public void crud(){
360
    	debug("\nStarting insert,update,delete document test ...");
361
        debug("-------------------------------------------------------");
362
    	try {
363
    		FileReader fr = new FileReader(insert_file);	
364
    		m.login(username,password);
365

    
366
    		debug("\nFirst insert the document...");
367
    		String response = m.putObject(newdocid+".1",fr,true);
368
    		debug("response:\n"+response);
369

    
370
    		fr = new FileReader(insert_file);
371
    		debug("\nNow update the document...");
372
    		response = m.putObject(newdocid+".2",fr,false);    	 
373
    		debug("response:\n"+response);    		
374
    		fr.close();
375
    		
376
    		Thread.sleep(10000);
377
    		
378
    		debug("\nFinally delete the document...");
379
    		response = m.deleteObject(newdocid+".2");  
380
    		debug("response:\n"+response);
381

    
382

    
383
    	} catch (MetacatAuthException mae) {
384
    		debug("Authorization failed:\n" + mae.getMessage());
385
    	} catch (MetacatInaccessibleException mie) {
386
    		debug("Metacat Inaccessible:\n" + mie.getMessage());
387
    	} catch (Exception e) {
388
    		e.printStackTrace();
389
    		fail("General exception:\n" + e.getMessage());
390
    	}
391
    }
392

    
393
    
394
    /**
395
     * Get the most recent document id for a given scope and be sure
396
     * that it matches the one we last inserted. Assumes this test is run
397
     * immediately following a successful insert() test.
398
     */
399
    public void getNextObject() {
400
        debug("\nStarting getNextObject test...");
401
        debug("-------------------------------------------------------");
402
        try {
403

    
404
            String lastId = m.getNextObject(prefix);
405
            debug("getNextObject(): Last Id=" + lastId);
406

    
407
        } catch (MetacatException me) {
408
            fail("Metacat Error:\n" + me.getMessage());
409
        } catch (Exception e) {
410
            fail("General exception:\n" + e.getMessage());
411
        }
412
    }
413

    
414
    /**
415
     * Get the most recent document id for a given scope and be sure
416
     * that it matches the one we last inserted. Assumes this test is run
417
     * immediately following a successful insert() test.
418
     */
419
    public void getNextRevision() {
420
        debug("\nStarting getNextRevision test...");
421
        debug("-------------------------------------------------------");
422
        try {
423

    
424
            int rev_id = m.getNextRevision(public_doc_id);
425
            debug("NextRevision number is " + rev_id);
426

    
427
        } catch (MetacatException me) {
428
            fail("Metacat Error:\n" + me.getMessage());
429
        } catch (Exception e) {
430
            fail("General exception:\n" + e.getMessage());
431
        }
432
    }
433
    
434
    
435
    /**
436
     * Test getAllDocids function
437
     */
438
    public void getAllDocids() {
439
        debug("\nStarting getAllDocids test...");
440
        debug("-------------------------------------------------------");
441
        try {
442

    
443
            Vector<String> vector = m.getAllDocids(prefix);
444
            StringBuffer b = new StringBuffer();
445
            for (String doc_id:vector)
446
            	b.append(doc_id+"\n");
447
            debug("getAllDocids():\n " + b.toString());
448

    
449
        } catch (MetacatException me) {
450
            fail("Metacat Error:\n" + me.getMessage());
451
        } catch (Exception e) {
452
            fail("General exception:\n" + e.getMessage());
453
        }
454
    }
455
    
456
    /***
457
     * Test isRegistered function
458
     */
459
    public void isRegistered() {
460
        debug("\nStarting isRegistered test...");
461
        debug("-------------------------------------------------------");
462
        try {
463
            boolean registered = m.isRegistered(public_doc_id);
464
            debug("isRegistered(): " + public_doc_id+" is "+(registered?"":"not ")+"registered"); 
465
            registered = m.isRegistered(newdocid);
466
            debug("isRegistered(): " + newdocid+" is "+(registered?"":"not ")+"registered");
467
        } catch (MetacatException me) {
468
            fail("Metacat Error:\n" + me.getMessage());
469
        } catch (Exception e) {
470
            fail("General exception:\n" + e.getMessage());
471
        }
472
    }
473
    
474
    /***
475
     * Test addLSID function
476
     */
477
    public void addLSID() {
478
    	  debug("\nStarting addLSID test...");
479
    	  debug("-------------------------------------------------------");
480
          try {
481
        	  String response =  m.addLSID(public_doc_id);
482
        	  debug("response:\n"+response);
483
          } catch (MetacatException me) {
484
              fail("Metacat Error:\n" + me.getMessage());
485
          } catch (Exception e) {
486
              fail("General exception:\n" + e.getMessage());
487
          }
488
    }
489
    	
490
    	
491
    /**
492
     * Create a hopefully unique docid for testing insert and update. Does
493
     * not include the 'revision' part of the id.
494
     *
495
     * @return a String docid based on the current date and time
496
     */
497
    private String generateDocid()
498
    {
499
    	StringBuffer docid = new StringBuffer(prefix);
500
    	docid.append(".");
501

    
502
    	// Create a calendar to get the date formatted properly
503
    	String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
504
    	SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
505
    	pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2*60*60*1000);
506
    	pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2*60*60*1000);
507
    	Calendar calendar = new GregorianCalendar(pdt);
508
    	Date trialTime = new Date();
509
    	calendar.setTime(trialTime);
510

    
511
    	int time = 0; 
512

    
513
    	docid.append(calendar.get(Calendar.YEAR));
514

    
515
    	time = calendar.get(Calendar.DAY_OF_YEAR);
516
    	if(time < 10){
517
    		docid.append("0");
518
    		docid.append("0");
519
    		docid.append(time);
520
    	} else if(time < 100) {
521
    		docid.append("0");
522
    		docid.append(time);
523
    	} else {
524
    		docid.append(time);
525
    	}
526

    
527
    	time = calendar.get(Calendar.HOUR_OF_DAY);
528
    	if(time < 10){
529
    		docid.append("0");
530
    		docid.append(time);
531
    	} else {
532
    		docid.append(time);
533
    	}
534

    
535
    	time = calendar.get(Calendar.MINUTE);
536
    	if(time < 10){
537
    		docid.append("0");
538
    		docid.append(time);
539
    	} else {
540
    		docid.append(time);
541
    	}
542

    
543
    	time = calendar.get(Calendar.SECOND);
544
    	if(time < 10){
545
    		docid.append("0");
546
    		docid.append(time);
547
    	} else {
548
    		docid.append(time);
549
    	}
550

    
551
    	//sometimes this number is not unique, so we append a random number
552
    	int random = (new Double(Math.random()*100)).intValue();
553
    	docid.append(random);
554
    	return docid.toString();
555
    }
556
}
    (1-1/1)