@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = getId(req); if (id == null) { resp.setStatus(SC_BAD_REQUEST); return; } Movie movie; try { movie = gson.fromJson(req.getReader(), Movie.class); } catch (Exception ignore) { resp.setStatus(SC_BAD_REQUEST); return; } if (!isMovieValid(movie) || movie.getId() != null && !movie.getId().equals(id)) { resp.setStatus(SC_BAD_REQUEST); return; } movie.setId(id); Movie prevMovieVersion = service.updateMovie(movie); if (prevMovieVersion == null) { resp.setStatus(SC_NOT_FOUND); } }
@Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = getId(req); if (id == null) { resp.setStatus(SC_BAD_REQUEST); return; } service.deleteMovieById(id); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = getId(req); if (id == null) { resp.setStatus(SC_BAD_REQUEST); return; } Movie movie = service.getMovieById(id); if (movie == null) { resp.setStatus(SC_NOT_FOUND); return; } resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().append(gson.toJson(movie)); }
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Movie movie; try { movie = gson.fromJson(req.getReader(), Movie.class); } catch (Exception ignore) { resp.setStatus(SC_BAD_REQUEST); return; } if (!isMovieValid(movie) || movie.getId() != null) { resp.setStatus(SC_BAD_REQUEST); return; } Long id = service.addMovie(movie); resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); JsonWriter jsonWriter = gson.newJsonWriter(resp.getWriter()); jsonWriter.beginObject().name("id").value(id).endObject(); jsonWriter.close(); }