de.sainth.recipe.backend.rest.controller.FoodController.java Source code

Java tutorial

Introduction

Here is the source code for de.sainth.recipe.backend.rest.controller.FoodController.java

Source

/*
 * 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.FoodRepository;
import de.sainth.recipe.backend.rest.views.Food;
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("/foods")
public class FoodController {

    @Autowired
    FoodRepository repository;

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping()
    List<Food> getAll() {
        return repository.findAll();
    }

    @Secured({ "ROLE_USER", "ROLE_ADMIN" })
    @RequestMapping("{id}")
    Food get(@PathVariable("id") Long id) {
        return repository.findOne(id);
    }

    @Secured("ROLE_ADMIN")
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    void delete(@PathVariable("id") Long id) {
        repository.delete(id);
    }

    @Secured("ROLE_ADMIN")
    @RequestMapping(method = RequestMethod.POST)
    HttpEntity<Food> add(@Valid @RequestBody Food food) {
        Food f = repository.save(food);
        return new ResponseEntity<>(f, HttpStatus.CREATED);
    }

    @Secured("ROLE_ADMIN")
    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    HttpEntity<Food> update(@PathVariable("id") Long id, @Valid @RequestBody Food food) {
        if (id.equals(food.getId())) {
            if (repository.findOne(food.getId()) != null) {
                repository.save(food);
                return new ResponseEntity<>(food, HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

}