Java tutorial
/* * The MIT License * * Copyright 2016 Dmitry Noranovich javaeeeee (at) gmail (dot) com. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.javaeeeee.dropbookmarks.resources; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Strings; import com.javaeeeee.dropbookmarks.core.Bookmark; import com.javaeeeee.dropbookmarks.core.User; import com.javaeeeee.dropbookmarks.db.BookmarkDAO; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.beanutils.BeanUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A class to serve bookmarks data to users. * * @author Dmitry Noranovich javaeeeee (at) gmail (dot) com */ @Path("/bookmarks") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public class BookmarksResource { /** * Error message return in the case if PUT request body can not be parsed. */ public static final String WRONG_BODY_DATA_FORMAT = "Wrong body data format"; /** * Logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(BookmarksResource.class); /** * DAO to manipulate bookmarks. */ private final BookmarkDAO bookmarkDAO; /** * Constructor to initialize DAO. * * @param bookmarkDAO DAO to manipulate bookmarks. */ public BookmarksResource(final BookmarkDAO bookmarkDAO) { this.bookmarkDAO = bookmarkDAO; } /** * Method returns all bookmarks stored by a particular user. * * @param user Authenticated user with whose bookmarks we work. * @return list of bookmarks stored by a particular user. */ @GET @UnitOfWork public List<Bookmark> getBookmarks(@Auth User user) { return bookmarkDAO.findByUserId(user.getId()); } /** * Method returns single bookmark data. * * @param id the id of a bookmark. * @param user Authenticated user with whose bookmarks we work. * @return Optional containing a bookmark or empty Optional if the bookmark * was not found. */ @GET @Path("/{id}") @UnitOfWork public Optional<Bookmark> getBookmark(@PathParam("id") IntParam id, @Auth User user) { return bookmarkDAO.findByIdAndUserId(id.get(), user.getId()); } /** * Method to add new bookmarks. * * @param bookmark A bookmark to add * @param user Authenticated user with whose bookmarks we work. * @return The saved bookmark containing the id generated by the database. */ @POST @UnitOfWork public Bookmark addBookmark(@Valid @NotNull Bookmark bookmark, @Auth User user) { bookmark.setUser(user); return bookmarkDAO.save(bookmark); } /** * A method to modify an existing bookmark data. * * @param id the id of the bookmark to be modified. * @param jsonData Modifications in JSON format. * @param user Authenticated user with whose bookmarks we work. * @return Bookmark with modified fields or throws an exception if bookmark * was not found. */ @PUT @Path("/{id}") @UnitOfWork public Bookmark modifyBookmark(@PathParam("id") IntParam id, String jsonData, @Auth User user) { Bookmark bookmark = findBookmarkOrTrowException(id, user); // Update bookmark data ObjectMapper objectMapper = new ObjectMapper(); Map<String, String> changeMap = null; try { changeMap = objectMapper.readValue(jsonData, HashMap.class); purgeMap(changeMap); BeanUtils.populate(bookmark, changeMap); return bookmarkDAO.save(bookmark); } catch (IOException | IllegalAccessException | InvocationTargetException ex) { LOGGER.warn(WRONG_BODY_DATA_FORMAT, ex); throw new WebApplicationException(WRONG_BODY_DATA_FORMAT, ex, Response.Status.BAD_REQUEST); } finally { if (changeMap != null) { changeMap.clear(); } } } /** * A method to remove bookmarks. * * @param id the id of a bookmark to be deleted. * @param user Authenticated user with whose bookmarks we work. * @return Removed bookmark data or throws an exception if the bookmark with * the id provided was not found. */ @DELETE @Path("/{id}") @UnitOfWork public Bookmark deleteBookmark(@PathParam("id") IntParam id, @Auth User user) { Bookmark bookmark = findBookmarkOrTrowException(id, user); bookmarkDAO.delete(id.get()); return bookmark; } /** * A method to remove null and empty values from the change map. Necessary * if not fields in the changed object are filled. * * @param changeMap map of object field values. */ protected void purgeMap(final Map<String, String> changeMap) { changeMap.remove("id"); changeMap.entrySet().removeIf(entry -> Strings.isNullOrEmpty(entry.getValue())); } /** * Method looks for a bookmark by id and User id and returns the bookmark or * throws NotFoundException otherwise. * * @param id the id of a bookmark. * @param user the id of the owner. * @return Bookmark */ private Bookmark findBookmarkOrTrowException(IntParam id, @Auth User user) { Bookmark bookmark = bookmarkDAO.findByIdAndUserId(id.get(), user.getId()) .orElseThrow(() -> new NotFoundException("Bookmerk requested was not found.")); return bookmark; } }