Created
December 2, 2011 03:47
-
-
Save smanek/1421648 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Path("/students") | |
@Produces({MediaType.APPLICATION_JSON}) | |
public class StudentResource { | |
private static final ObjectMapper MAPPER = new ObjectMapper(); | |
// We'll just 'persist' data in memory for this test application | |
private static final Map<Integer, Student> STUDENTS = Maps.newConcurrentMap(); | |
@GET | |
public Collection<Integer> listStudentIds() { | |
return STUDENTS.keySet(); | |
} | |
@GET | |
@Path("{uid: [0-9]+}") | |
public Student getStudent(@PathParam("uid") int uid) { | |
final Student student = STUDENTS.get(uid); | |
// return a 404 if no user with the given UID exists | |
if (student == null) { | |
throw new WebApplicationException(Response.Status.NOT_FOUND); | |
} else { | |
return student; | |
} | |
} | |
@POST | |
@Consumes({MediaType.APPLICATION_FORM_URLENCODED}) | |
public int createStudent(@FormParam("name") String name, | |
@FormParam("dob") DateParam dateParam, | |
@FormParam("enrolled") @DefaultValue("true") boolean enrolled, | |
@FormParam("courses") @DefaultValue("") CsvParam csvCourses) throws IOException { | |
assert name != null && name.length() > 2 && name.length() < 100; | |
assert dateParam != null && dateParam.getValue() != null; | |
List<Course> courses = Lists.newLinkedList(); | |
for (String courseStr : csvCourses.getValue()) { | |
courses.add(MAPPER.readValue("\"" + courseStr + "\"", Course.class)); | |
} | |
final Student newStudent = new Student(name, dateParam.getValue(), enrolled, courses); | |
final Student oldStudent = STUDENTS.put(newStudent.getUid(), newStudent); | |
assert oldStudent == null; | |
return newStudent.getUid(); | |
} | |
@DELETE | |
@Path("{uid: [0-9]+}") | |
public boolean deleteStudent(@PathParam("uid") int uid) { | |
final Student deletedStudent = STUDENTS.remove(uid); | |
if (deletedStudent == null) { | |
throw new WebApplicationException(Response.Status.NOT_FOUND); | |
} else { | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment