Permalink
Browse files

Merge pull request #24 from ideoplex/work

Addition of unit tests using jersey-client 1.x
  • Loading branch information...
ideoplex committed Nov 1, 2015
2 parents e7bfbd4 + 51c3060 commit 5fd91650b576838127c5dbe96bb1096e7095bb86
@@ -1,14 +1,16 @@
jersey-gson
===========

Sample java web application with jersey and gson that displays a list of users in a [Datatables](http://datatables.net/) table.
Sample java web application with jersey and custom gson serialiation/deserialization
to displays a list of users in a [Datatables](http://datatables.net/) table.
The application retrieves the users via Datatables ajax.
User edits are submitted to the server and successful response is applied to the local data set in the browser.
Long cell text will be truncated with an ellipsis.

Users can be added via a [Bootstrap](http://getbootstrap.com/) Modal dialog. Users are kept in memory and are not persisted.

The application tests demonstrate the use of [Selenium](http://www.seleniumhq.org/) automation for the addition of users.
The application tests demonstrate the use of [Selenium](http://www.seleniumhq.org/) automation for the addition of users
and the use of jersey-client with gson.

The application can be run from the command line via:

@@ -17,7 +19,7 @@ mvn jetty:run
```

[Maven](https://maven.apache.org/) is configured to autostart/autostop jetty
for the selenium test. Please halt any "mvn jetty:run" invocations before
for tests. Please halt any "mvn jetty:run" invocations before
running the tests via:

```
@@ -32,6 +34,7 @@ mvn test -Dbrowser=chrome

Read about the project (from most recent to oldest):

1. [Jersey Client with Gson](https://ideoplex.com/2015/11/01/jersey-client-with-gson/)
1. [jersey-gson Content-Type Woes](https://ideoplex.com/2015/10/31/jersey-gson-content-type-woes/)
1. [Autostart Jetty in Maven](https://ideoplex.com/2015/10/25/autostart-jetty-in-maven/)
1. [DataTables, Bootstrap and Text Overflow](https://ideoplex.com/2015/08/16/datatables-bootstrap-and-text-overflow/)
@@ -122,9 +122,16 @@
<version>${selenium.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.client.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.12</jersey.version>
<jersey.client.version>1.18</jersey.client.version>
<jetty.version>9.3.0.M2</jetty.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<testng.version>6.9.4</testng.version>
@@ -28,12 +28,16 @@


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Singleton
public class GsonReader<T> implements MessageBodyReader<T> {
protected static Gson gson = new GsonBuilder()
.registerTypeAdapter(UserMap.class,new UserMapUnmarshall())
.create();

@Override
public boolean isReadable(Class<?> type, Type genericType,
@@ -46,8 +50,7 @@ public T readFrom(Class<T> type, Type genericType,
Annotation[] antns, MediaType mt,
MultivaluedMap<String, String> mm, InputStream in)
throws IOException, WebApplicationException {
Gson g = new Gson();
return g.fromJson(_convertStreamToString(in), type);
return gson.fromJson(_convertStreamToString(in), type);
}

private String _convertStreamToString(InputStream inputStream)
@@ -1,8 +1,10 @@
package com.ideoplex.tutorial;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
@@ -61,6 +63,32 @@ public User getUserTemplate() {
return user;
}

@GET
@Path("user/get/{email}")
@Produces(MediaType.APPLICATION_JSON)
public User getUser(@PathParam("email") String email) {
User rVal = users.get(email);
if ( rVal == null ) {
throw new WebApplicationException(Response
.status(Response.Status.NOT_FOUND)
.build());
}
return rVal;
}

@DELETE
@Path("user/delete/{email}")
@Produces(MediaType.APPLICATION_JSON)
public User deleteUser(@PathParam("email") String email) {
User rVal = users.remove(email);
if ( rVal == null ) {
throw new WebApplicationException(Response
.status(Response.Status.NOT_FOUND)
.build());
}
return rVal;
}

@POST
@Path("user/post")
@Consumes(MediaType.APPLICATION_JSON)
@@ -0,0 +1,41 @@
package com.ideoplex.tutorial;


import java.lang.reflect.Type;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonElement;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonDeserializationContext;


public class UserMapUnmarshall implements JsonDeserializer<UserMap> {
private static Gson gson = new Gson();

@Override
public UserMap deserialize(JsonElement mapFormat, Type typeOfSrc, JsonDeserializationContext context) {
Iterator<JsonElement> iterate = mapFormat.getAsJsonObject()
.get("data")
.getAsJsonArray()
.iterator();

UserMap users = new UserMap();
while( iterate.hasNext() ) {
JsonObject user = ((JsonElement) iterate.next()).getAsJsonObject();
String email = user.get("email").getAsString();
User add = new User();
add.setEmail( email );
add.setSurname( user.get("surname").getAsString() );
add.setGivenName( user.get("givenName").getAsString() );
users.put( email, add );
}

return users;
}
}
@@ -76,7 +76,7 @@ public void addUsers( WebDriver driver )
}

@Parameters({"browser","baseurl","waitajax"})
@Test(invocationCount = 2, groups="browser")
@Test(invocationCount = 2, dependsOnGroups="client", groups="browser")
public void userCreate( String browser, String baseurl, String waitajax )
{
WebDriver driver = "chrome".equalsIgnoreCase(browser)
@@ -0,0 +1,90 @@
package com.ideoplex.tutorial;


import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

import org.testng.Assert;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;


public class ClientTest {

public static final String className = ClientTest.class.getName();

@Parameters({"baseurl"})
@Test(groups="client")
public void userCreate( String baseurl )
{
final User sample;
final String email;
final String url;

Client client;
WebResource resource;
ClientResponse response;

{
email = "test@" + className;
sample = new User();
sample.setEmail(email);
sample.setGivenName("John Q.");
sample.setSurname("Public");

url = baseurl + "webapi/myresource/user";

ClientConfig config = new DefaultClientConfig();
config.getClasses().add(GsonReader.class);
config.getClasses().add(GsonWriter.class);

client = Client.create(config);
}

{
System.out.println("Verify that " + email + " is not available yet");
resource = client.resource( url + "/get/" + email );
response = resource.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assert( response.getStatus() == 404 );
}

{
System.out.println("Verify that user/post on " + email + " succeeds");
resource = client.resource( url + "/post" );
response = resource.accept(MediaType.APPLICATION_JSON)
.type(MediaType.APPLICATION_JSON)
.post(ClientResponse.class,sample);
assert( response.getStatus() == 200 );
User rVal = response.getEntity(User.class);
assert( email.equals(rVal.getEmail()) );
}

{
System.out.println("Verify that " + email + " is in the userMap");
resource = client.resource( url + "/map" );
response = resource.accept(MediaType.APPLICATION_JSON)
.get(ClientResponse.class);
assert( response.getStatus() == 200 );
UserMap rVal = response.getEntity(UserMap.class);
assert( rVal != null );
User look = rVal.get(email);
assert( look != null );
}

{
System.out.println("Verify that delete on " + email + " succeeds");
resource = client.resource( url + "/delete/" + email );
response = resource.accept(MediaType.APPLICATION_JSON)
.delete(ClientResponse.class);
assert( response.getStatus() == 200 );
User rVal = response.getEntity(User.class);
assert( email.equals(rVal.getEmail()) );
}
}
}

0 comments on commit 5fd9165

Please sign in to comment.