Posts Tagged javaee
Jersey 1.0.2 JSON and JAXB
In a previous post I explained how to unit test JAX-RS. Let’s now have a look at a more complex example: implementing RESTful webservices using Jersey 1.0.2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <servlet> <servlet-name>My Jersey Web Application</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name> <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>net.tmro.demo.json;your.packages;separated.by.semicolons</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>My Jersey Web Application</servlet-name> <url-pattern>/webappjson/*</url-pattern> </servlet-mapping> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package net.tmro.demo.json; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @Path(“/myresource”) public class MyResource { public MyResource() { } @GET @Produces(value=MediaType.APPLICATION_JSON) @Path(“/getsomething”) public MyComplexObject getSomething(@QueryParam(“idOfSomething”) String id) { //your complex object can expose primitive data types, objects as well as collections. //you are not required to do anything fancy as long as you implement return new MyComplexObject(id); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package net.tmro.demo.json; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.*; import javax.ws.rs.ext.*; import com.sun.jersey.spi.resource.Singleton; import net.sf.json.JSONSerializer; @Provider @Singleton public class MyEntityProvider implements MessageBodyWriter<object> { //the json serializer used to write out objects to the output stream private final JSONSerializer serializer = new JSONSerializer(); public long getSize(final Object t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return -1; } public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) { return mediaType.isCompatible(MediaType.APPLICATION_JSON_TYPE); } public void writeTo(final Object t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<string, Object> httpHeaders, final OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write(serializer.toJSON(t).toString().getBytes()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | package net.tmro.demo.json; @XmlRootElement public class MyComplexObject extends AnotherObject { //fields: primitive data types, objects and collections. everything gets serialized unless //marked as transient public MyComplexObject(String id){ [..] } //getters and setters } |
OpenJPA – LL
Posted by Nick in Uncategorized on May 17, 2009
Note to self: when using OpenJPA and lazy loading just remember that the info is actually fetched when calling the getter. Direct access to fields will not load the associated entity.
Unit Test JAX-RS using Java 6 and JUnit 4
Today I was amazed to discover that Unit testing JAX-RS resources with JUnit 4 and Java 6 is insanely easy.
Have a look at the example below and then read the description underneath if things are not clear enough already.
import static org.junit.Assert.*;
import java.io.*;
import java.net.*;
import javax.ws.rs.*;
import org.junit.*;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.net.httpserver.HttpServer;
@Path("/hellotest")
public class MyResourceTest {
private static final String LOCALHOST = "http://localhost:9998/";
private static HttpServer server;
@GET
@Produces("text/plain")
public String testSystem(){
return "Hello. This is a test";
}
@BeforeClass
public static void setUp() throws Exception{
System.out.println("Creating server");
server = HttpServerFactory.create(LOCALHOST);
System.out.println("Starting server");
server.start();
System.out.println("HTTP server started");
System.out.println("Running tests...");
testResourceAtUrl(new URL(LOCALHOST + "hellotest"));
}
private static String testResourceAtUrl(URL url) throws Exception {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String firstLineOfText = reader.readLine();//you can also read the whole thing and then test
System.out.println("Read: " + firstLineOfText);
System.out.println("System was initialized correctly. About to run actual tests...");
connection.disconnect();
return firstLineOfText;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
throw new Exception("could not establish connection to " + url.toExternalForm());
}
@Test
public void testMyMethod() throws Exception {
String activationText = testResourceAtUrl(new URL(LOCALHOST + "myresource"));
//TODO test here
}
/**
* Destroy the server
*/
@AfterClass
public static void tearDown() throws IOException{
System.out.println("Stopping server");
server.stop(0);
System.out.println("Server stopped");
}
}
So here’s what the code above means:
1. @Path(”/hellotest”) The unit test itself is set up as a resource so when the tests are run we can check that the system is working by consuming the resource defined by testSystem()
2. Java 6 allows us to set up a HTTP server very easily using HttpServerFactory.create(LOCALHOST) This way we simply go ahead and send HTTP requests without having to worry about 3rd party libs and setting up mock HTTP servers.
3. testResourceAtUrl(new URL(LOCALHOST + “hellotest”)) does the hard work: it requests the resource from the location that we specify in the method call.
4. put your actual test data in the placeholder
Of course this is a simplified test, and it is meant just to show you how easy it is to test your RESTful webservices. How would you make this better?
Cheers…

Recent Comments