Skip to content

Instantly share code, notes, and snippets.

@up1
Last active August 29, 2015 14:02
Show Gist options
  • Save up1/f6813deef8bfe1ec25ca to your computer and use it in GitHub Desktop.
Save up1/f6813deef8bfe1ec25ca to your computer and use it in GitHub Desktop.
Demo :: Create RESTful Web Service with Jersey
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-grizzly2 \
-DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false \
-DgroupId=com.rest.demo -DartifactId=first-demo -Dpackage=com.rest.demo \
-DarchetypeVersion=2.9
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.9</version>
</dependency>
package com.rest.demo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("myresource")
public class MyResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}
}
package com.rest.demo;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MyResourceTest {
private HttpServer server;
private WebTarget target;
@Before
public void setUp() throws Exception {
server = Main.startServer();
Client c = ClientBuilder.newClient();
target = c.target(Main.BASE_URI);
}
@After
public void tearDown() throws Exception {
server.stop();
}
@Test
public void testGetIt() {
String responseMsg = target.path("myresource").request().get(String.class);
assertEquals("Got it!", responseMsg);
}
}
package com.rest.demo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("person")
public class Person {
@GET
@Produces(MediaType.APPLICATION_JSON)
public PersonValue getAll() {
return new PersonValue(1, "UP1");
}
}
@Test
public void getPersonDetail() {
PersonValue expectedResult = new PersonValue(1, "UP1");
PersonValue personValue = target.path("person").request().get(PersonValue.class);
assertEquals(expectedResult.getId(), personValue.getId());
assertEquals(expectedResult.getName(), personValue.getName());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment