Java tutorial
/* * Copyright (c) 2017 sainth (sainth@sainth.de) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package de.sainth.recipe.backend.rest.controller; import de.sainth.recipe.backend.db.repositories.UnitRepository; import de.sainth.recipe.backend.rest.views.Unit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/units") public class UnitController { @Autowired UnitRepository repository; @Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping() List<Unit> getAll() { return repository.findAll(); } @Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping("{shortname}") Unit get(@PathVariable("shortname") String shortname) { return repository.findOne(shortname); } @Secured("ROLE_ADMIN") @RequestMapping(value = "{shortname}", method = RequestMethod.DELETE) @ResponseStatus(HttpStatus.NO_CONTENT) void delete(@PathVariable("shortname") String shortname) { repository.delete(shortname); } @Secured("ROLE_ADMIN") @RequestMapping(method = RequestMethod.POST) HttpEntity<Unit> add(@Valid @RequestBody Unit unit) { Unit u = repository.save(unit); return new ResponseEntity<>(u, HttpStatus.CREATED); } @Secured("ROLE_ADMIN") @RequestMapping(value = "{shortname}", method = RequestMethod.PUT) HttpEntity<Unit> update(@PathVariable("shortname") String shortname, @Valid @RequestBody Unit unit) { if (shortname.equals(unit.getShortname())) { if (repository.findOne(unit.getShortname()) != null) { repository.save(unit); return new ResponseEntity<>(unit, HttpStatus.OK); } } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }