KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > cluster > httpsessionreplication > HttpSessionReplicationUnitTestCase


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.test.cluster.httpsessionreplication;
23
24 import java.io.BufferedReader JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.URLConnection JavaDoc;
29 import java.util.Properties JavaDoc;
30
31 import junit.framework.Test;
32
33 import org.apache.commons.httpclient.HttpClient;
34 import org.apache.commons.httpclient.HttpMethod;
35 import org.apache.commons.httpclient.HttpRecoverableException;
36 import org.apache.commons.httpclient.methods.GetMethod;
37 import org.jboss.test.JBossClusteredTestCase;
38  
39 /**
40  *
41  * @see org.jboss.test.cluster.httpsessionreplication
42  *
43  * @author <a HREF="mailto:anil.saldhana@jboss.com">Anil Saldhana</a>.
44  * @version $Revision: 1.0
45  */

46 public class HttpSessionReplicationUnitTestCase
47 extends JBossClusteredTestCase {
48     /**
49      * The Servernames should be configurable.
50      */

51     private String JavaDoc[] servernames= {"jnp://localhost:1099", "jnp://localhost:1199"};
52     
53     /**
54      * The main properties file that should be under src/resources/cluster
55      */

56     private Properties JavaDoc prop = null;
57     
58     /**
59      * Denotes number of nodes in the cluster test
60      */

61     private int numInstances = 0;
62     
63     public HttpSessionReplicationUnitTestCase (String JavaDoc name) {
64           super(name);
65           try{
66             this.getPropertiesFile();
67              String JavaDoc numin = prop.getProperty("NumOfInstances");
68              numInstances = Integer.parseInt( numin );
69              if( numInstances < 2 ) fail( "Atleast two nodes needed");
70              
71              //Lets build up the jndi server urls now
72
this.setServerNames(servernames);
73             }catch( Exception JavaDoc e){
74                 fail( e.getMessage());
75             }
76     }
77     
78     public static Test suite() throws Exception JavaDoc
79     {
80         //The following jar deployment is a dummy.
81
Test t1 = JBossClusteredTestCase.getDeploySetup(HttpSessionReplicationUnitTestCase.class,
82                                     "httpsessionreplication.jar");
83           return t1;
84     }
85     
86     /**
87      * Tests connection to the Apache Server.
88      * Note: We deal with just one Apache Server. We can bounce the different
89      * JBoss/Tomcat servers and Apache will loadbalance.
90      * @throws Exception
91      */

92     public void testApacheConnection()
93     throws Exception JavaDoc
94     {
95         getLog().debug("Enter testApacheConnection");
96         try {
97             // makeConnection( "http://localhost");
98
this.makeConnection(prop.getProperty("ApacheUrl"));
99         } catch (Exception JavaDoc e) {
100         }
101         getLog().debug("Exit testApacheConnection");
102     }
103     
104     /**
105      * Main method that deals with the Http Session Replication Test
106      * @throws Exception
107      */

108     public void testHttpSessionReplication()
109     throws Exception JavaDoc
110     {
111         String JavaDoc attr = "";
112         getLog().debug("Enter testHttpSessionReplication");
113         //First need to make a Http Connection to Apache and get the session id
114
//Then bring down the first instance and make another call
115
//Then check the session id or just see if the server has not returned an error
116
//String urlname = "http://localhost/testsessionreplication.jsp";
117
//String geturlname = "http://localhost/getattribute.jsp";
118

119         String JavaDoc urlname = prop.getProperty("SetAttrUrl");
120         String JavaDoc geturlname = prop.getProperty("GetAttrUrl");
121         /*
122         makeConnection(urlname);
123         getHttpText( urlname );
124         
125         //Get the Attribute set by testsessionreplication.jsp
126         attr= getAttribute( geturlname );
127         //Shut down the first instance
128         shutDownInstance( "localhost:1099");
129         //Give 30 seconds for things to stabilize.
130         sleepThread(30*1000);//30 seconds
131         if( !getAttribute(geturlname).equals(attr)) fail("Http Session Replication Failed");
132         getLog().debug("Http Session Replication has happened");
133         getLog().debug("Exit testHttpSessionReplication");
134         */

135         
136 // Create an instance of HttpClient.
137
HttpClient client = new HttpClient();
138
139       // Create a method instance.
140
HttpMethod method = new GetMethod(urlname);
141       String JavaDoc str = makeGet( client, method );
142       
143       //Make a second connection
144
method = new GetMethod(geturlname);
145
146 // Get the Attribute set by testsessionreplication.jsp
147
attr= makeGet( client,method );
148 // Shut down the first instance
149
//shutDownInstance( "localhost:1099");
150
shutDownInstance( 1 );
151       getLog().debug( "Brought down the first instance");
152 // Give 30 seconds for things to stabilize.
153
sleepThread(30*1000);//30 seconds
154

155 // Make connection
156
method = new GetMethod(geturlname);
157       String JavaDoc attr2= makeGet( client, method );
158       if( ! attr2.equals(attr)) fail("Http Session Replication Failed");
159       getLog().debug("Http Session Replication has happened");
160       getLog().debug("Exit testHttpSessionReplication");
161     }
162
163     /**
164      * Reads in the properties file
165      */

166     public void getPropertiesFile(){
167         prop = new Properties JavaDoc();
168         try{
169             java.net.URL JavaDoc url = ClassLoader.getSystemResource("cluster/cluster-test.properties");
170             prop.load( url.openStream());
171         }catch( Exception JavaDoc e){
172             fail("Need a properties file under src/resources/cluster:"+e.getMessage());
173         }
174     }
175     
176     /**
177      * Shuts down an instance of JBoss.
178      * @throws Exception
179      */

180     private void shutDownInstance(int instancenum)
181     throws Exception JavaDoc
182     {
183         String JavaDoc command = getCommand(instancenum);
184         
185         getLog().debug("Going to execute:"+command);
186         Process JavaDoc child = Runtime.getRuntime().exec(command);
187         sleepThread( 10*1000 );
188         getLog().debug("Process exit value="+child.exitValue());
189      }
190     
191     /**
192      * Generate the command to run to shutdown a jboss node
193      * @param instancenum
194      * @return
195      */

196     private String JavaDoc getCommand( int instancenum) {
197         //String base="/Users/anil/jboss-head/build/output/jboss-4.0.0DR4";
198
//String cpath = base+"/bin/shutdown.jar:"+base+"/client/jbossall-client.jar";
199
//String command = "java -server -Xms128m -Xmx128m -classpath "+" org.jboss.Shutdown -s "+jndiurl;
200
//String command = base+"/bin/shutdown.sh -s "+jndiurl;
201
String JavaDoc command = "";
202         try{
203             command = prop.getProperty("jboss.location") + prop.getProperty("ShutDownScript");
204             command += " -s " + "jnp://"+prop.getProperty("Instance"+instancenum+".host")+":"+
205                                 prop.getProperty("Instance"+instancenum+".port.jndi");
206         }catch( Exception JavaDoc e){
207             fail( "getCommand Failed with:"+ e.getMessage());
208         }
209         
210         return command;
211     }
212
213     /**
214      * Sleep for specified time
215      * @param millisecs
216      * @throws Exception
217      */

218     private void sleepThread(long millisecs)
219     throws Exception JavaDoc {
220         Thread.sleep(millisecs);
221     }
222     
223     /**
224      * Makes a HTTP Connection
225      * @param urlname
226      * @throws Exception
227      */

228     private void makeConnection( String JavaDoc urlname )
229     throws Exception JavaDoc
230     {
231         getLog().debug("Enter makeConnection");
232         try {
233             // Step 1: Create URLConnection for URL
234
URL JavaDoc url = new URL JavaDoc(urlname);
235             URLConnection JavaDoc conn = url.openConnection();
236          
237             // List all the response headers from the server.
238
for (int i=0; ; i++) {
239                 String JavaDoc hname = conn.getHeaderFieldKey(i);
240                 String JavaDoc hvalue = conn.getHeaderField(i);
241                
242                 getLog().debug("hname="+hname+"::"+"value="+hvalue);
243                 if (hname == null && hvalue == null) {
244                     // No more headers
245
break;
246                 }
247                 if (hname == null) {
248                        getLog().debug("Response from Apache="+hvalue);
249                     // The header value contains the server's HTTP version
250
if( hvalue.indexOf("200") < 0 && hvalue.indexOf("301") < 0
251                             && hvalue.indexOf("302") < 0)
252                             fail(urlname+" Down");
253                        break;
254                 }
255             }
256         } catch (Exception JavaDoc e) {
257                 getLog().debug(e);
258         }
259     }
260
261     /**
262      * This method gets the response from the HTTP Server provided an URl
263      * @param urlname
264      */

265      private void getHttpText( String JavaDoc urlname ){
266         getLog().debug( getAttribute(urlname));
267     }//end method
268

269      /**
270       * Returns the attribute set on the session
271       * Refer to getattribute.jsp
272       * @param urlname
273       * @return
274       */

275     private String JavaDoc getAttribute( String JavaDoc urlname){
276         BufferedReader JavaDoc in = null;
277         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
278         try{
279                 URL JavaDoc url = new URL JavaDoc(urlname);
280             
281              //Read all the text returned by the server
282
in = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(url.openStream()));
283             String JavaDoc str;
284             while ((str = in.readLine()) != null) {
285             // str is one line of text; readLine() strips the newline character(s)
286
sb.append(str);
287         }
288             getLog().debug(sb.toString());
289         }catch( Exception JavaDoc e){
290            getLog().debug( e);
291         }finally{
292              try{
293                  in.close();
294              }catch(Exception JavaDoc y){}
295         }
296         return sb.toString();
297      }
298      
299      /**
300       * Makes a http call to the jsp that retrieves the attribute stored on the
301       * session. When the attribute values mathes with the one retrieved earlier,
302       * we have HttpSessionReplication.
303       * Makes use of commons-httpclient library of Apache
304      * @param client
305      * @param method
306      * @return session attribute
307      * @throws IOException
308      */

309     private String JavaDoc makeGet( HttpClient client, HttpMethod method) throws IOException JavaDoc{
310        // Execute the method.
311
int statusCode = -1;
312      
313         try {
314            // execute the method.
315
statusCode = client.executeMethod(method);
316          } catch (HttpRecoverableException e) {
317            System.err.println(
318              "A recoverable exception occurred, retrying." +
319              e.getMessage());
320          } catch (IOException JavaDoc e) {
321            System.err.println("Failed to download file.");
322            e.printStackTrace();
323            System.exit(-1);
324          }
325
326        // Read the response body.
327
byte[] responseBody = method.getResponseBody();
328
329        // Release the connection.
330
method.releaseConnection();
331
332        // Deal with the response.
333
// Use caution: ensure correct character encoding and is not binary data
334
return new String JavaDoc(responseBody);
335    }
336     
337     /*
338      * Override the method and do nothing. It fails when we run this testcase
339      * because we have brought down instances.
340      * @see org.jboss.test.JBossTestCase#testServerFound()
341      */

342     public void testServerFound() throws Exception JavaDoc
343     {
344     }
345
346 }
347
Popular Tags