|
| 1 | +package com.baeldung.cxf.jaxrs.implementation; |
| 2 | + |
| 3 | +import javax.ws.rs.*; |
| 4 | +import javax.ws.rs.core.Response; |
| 5 | +import java.util.ArrayList; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | + |
| 10 | +@Path("baeldung") |
| 11 | +@Produces("text/xml") |
| 12 | +public class CourseRepository { |
| 13 | + private Map<Integer, Course> courses = new HashMap<>(); |
| 14 | + |
| 15 | + { |
| 16 | + Student student1 = new Student(); |
| 17 | + Student student2 = new Student(); |
| 18 | + student1.setId(1); |
| 19 | + student1.setName("Student A"); |
| 20 | + student2.setId(2); |
| 21 | + student2.setName("Student B"); |
| 22 | + |
| 23 | + List<Student> course1Students = new ArrayList<>(); |
| 24 | + course1Students.add(student1); |
| 25 | + course1Students.add(student2); |
| 26 | + |
| 27 | + Course course1 = new Course(); |
| 28 | + Course course2 = new Course(); |
| 29 | + course1.setId(1); |
| 30 | + course1.setName("REST with Spring"); |
| 31 | + course1.setStudents(course1Students); |
| 32 | + course2.setId(2); |
| 33 | + course2.setName("Learn Spring Security"); |
| 34 | + |
| 35 | + courses.put(1, course1); |
| 36 | + courses.put(2, course2); |
| 37 | + } |
| 38 | + |
| 39 | + @GET |
| 40 | + @Path("courses/{courseId}") |
| 41 | + public Course getCourse(@PathParam("courseId") int courseId) { |
| 42 | + return findById(courseId); |
| 43 | + } |
| 44 | + |
| 45 | + @PUT |
| 46 | + @Path("courses/{courseId}") |
| 47 | + public Response updateCourse(@PathParam("courseId") int courseId, Course course) { |
| 48 | + Course existingCourse = findById(courseId); |
| 49 | + if (existingCourse == null) { |
| 50 | + return Response.status(Response.Status.NOT_FOUND).build(); |
| 51 | + } |
| 52 | + if (existingCourse.equals(course)) { |
| 53 | + return Response.notModified().build(); |
| 54 | + } |
| 55 | + courses.put(courseId, course); |
| 56 | + return Response.ok().build(); |
| 57 | + } |
| 58 | + |
| 59 | + @Path("courses/{courseId}/students") |
| 60 | + public Course pathToStudent(@PathParam("courseId") int courseId) { |
| 61 | + return findById(courseId); |
| 62 | + } |
| 63 | + |
| 64 | + private Course findById(int id) { |
| 65 | + for (Map.Entry<Integer, Course> course : courses.entrySet()) { |
| 66 | + if (course.getKey() == id) { |
| 67 | + return course.getValue(); |
| 68 | + } |
| 69 | + } |
| 70 | + return null; |
| 71 | + } |
| 72 | +} |
0 commit comments