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.BasicUnitRepository; import de.sainth.recipe.backend.rest.views.BasicUnit; 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("/basicUnits") public class BasicUnitController { private final BasicUnitRepository repository; @Autowired public BasicUnitController(BasicUnitRepository repository) { this.repository = repository; } @Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping() List<BasicUnit> getAll() { return repository.findAll(); } @Secured({ "ROLE_USER", "ROLE_ADMIN" }) @RequestMapping(value = "{shortname}") BasicUnit 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<BasicUnit> add(@Valid @RequestBody BasicUnit basicUnit) { BasicUnit bu = repository.save(basicUnit); return new ResponseEntity<>(bu, HttpStatus.CREATED); } @Secured("ROLE_ADMIN") @RequestMapping(value = "{shortname}", method = RequestMethod.PUT) HttpEntity<BasicUnit> update(@PathVariable("shortname") String shortname, @Valid @RequestBody BasicUnit basicUnit) { if (shortname.equals(basicUnit.getShortname())) { if (repository.findOne(basicUnit.getShortname()) != null) { repository.save(basicUnit); return new ResponseEntity<>(basicUnit, HttpStatus.OK); } } return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } }