CXF Webservice Using Embedded Jetty

In this tutorial we are going to test a webservice using embedded Jetty instance and JUnit. Here we are testing a simple REST service implemented by CXF framework, It works as a standalone application.
CXF Webservice Using embedded Jetty
Jetty provides a Web server and javax.servlet container, plus support for SPDY, WebSocket, OSGi, JMX, JNDI, JAAS and many other integration. These components are open source and available for commercial use and distribution
Reference -> http://www.eclipse.org/jetty/
Required Libraries
You need to download
- hamcrest-core-1.3.jar (Required for JUnit)
- jetty-all-8.1.2.v20120308.jar
- servlet-api-3.1.jar
- CXFRestfulTutorial.war [generating war, please check -> http://www.javatips.net/blog/cxf-restful-tutorial]
Project Structure
Testing REST service with an embedded Jetty instance
Here we are using JUnit and embedded Jetty for testing different rest methods (getName-> GET & changeName-> POST). We are attaching CXFRestfulTutorial.war programmatically and this war contains all the rest methods(getName & changeName) we are going to test.
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.webapp.WebAppContext;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class EmbeddedJettyIT {
protected static Server server;
@BeforeClass
public static void setUp() throws Exception {
server = new Server();
Connector connector = new SelectChannelConnector();
connector.setPort(9000);
server.setConnectors(new Connector[] { connector });
WebAppContext wactx = new WebAppContext();
wactx.setContextPath("/CXFRestfulTutorial");
wactx.setWar("CXFRestfulTutorial.war");
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[] { wactx, new DefaultHandler() });
server.setHandler(handlers);
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetMethod() throws InterruptedException, ExecutionException {
try {
URL url = new URL("http://localhost:9000/CXFRestfulTutorial/rest/getName");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
Scanner scanner;
String response;
if (conn.getResponseCode() != 200) {
scanner = new Scanner(conn.getErrorStream());
response = "Error From Server \n\n";
} else {
scanner = new Scanner(conn.getInputStream());
response = "Response From Server \n\n";
}
scanner.useDelimiter("\\Z");
System.out.println(response + scanner.next());
scanner.close();
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testPostMethod() throws InterruptedException,
ExecutionException {
try {
URL url = new URL("http://localhost:9000/CXFRestfulTutorial/rest/changeName");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"Student\":{\"name\":\"Tom\"}}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
Scanner scanner;
String response;
if (conn.getResponseCode() != 200) {
scanner = new Scanner(conn.getErrorStream());
response = "Error From Server \n\n";
} else {
scanner = new Scanner(conn.getInputStream());
response = "Response From Server \n\n";
}
scanner.useDelimiter("\\Z");
System.out.println(response + scanner.next());
scanner.close();
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@AfterClass
public static void tearDown() throws Exception {
if (server != null) {
server.stop();
server.destroy();
server = null;
}
}
}
Output
INFO: Root WebApplicationContext: initialization completed in 854 ms 2014-10-23 08:07:48.027:INFO:oejsh.ContextHandler:started o.e.j.w.WebAppContext{/CXFRestfulTutorial,file:/tmp/jetty-0.0.0.0-9000-CXFRestfulTutorial.war-_CXFRestfulTutorial-any-/webapp/},CXFRestfulTutorial.war 2014-10-23 08:07:48.050:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:9000 Response From Server {"Student":{"name":"HELLO Tom"}} Response From Server {"Student":{"name":"Rockey"}} 2014-10-23 08:07:48.359:INFO:/CXFRestfulTutorial:Closing Spring root WebApplicationContext Oct 23, 2014 8:07:48 AM org.springframework.context.support.AbstractApplicationContext doClose INFO: Closing Root WebApplicationContext: startup date [Thu Oct 23 08:07:47 IST 2014]; root of context hierarchy Oct 23, 2014 8:07:48 AM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4b5b3ba5: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,base,StudentService]; root of factory hierarchy 2014-10-23 08:07:48.365:INFO:oejsh.ContextHandler:stopped o.e.j.w.WebAppContext{/CXFRestfulTutorial,file:/tmp/jetty-0.0.0.0-9000-CXFRestfulTutorial.war-_CXFRestfulTutorial-any-/webapp/},CXFRestfulTutorial.war