com.sandbox.recipe.service.RecipeController.java Source code

Java tutorial

Introduction

Here is the source code for com.sandbox.recipe.service.RecipeController.java

Source

/* Copyright 2017 Philip Polasek. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
package com.sandbox.recipe.service;

import com.sandbox.recipe.domain.HistoryItem;
import com.sandbox.recipe.domain.Recipe;
import com.sandbox.recipe.domain.RecipeTag;
import com.sandbox.recipe.domain.SearchCriteria;
import com.sandbox.recipe.repository.CookbookRepository;
import com.sandbox.recipe.repository.HistoryItemRepository;
import com.sandbox.recipe.repository.RecipeRepository;
import com.sandbox.recipe.repository.RecipeTagRepository;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * --- TODO: Class comments go here ---
 *
 * <b><pre>
 * Copyright 2017 Philip Polasek.
 * All rights reserved.
 * </pre></b>
 *
 * @author ppolasek
 */
@RestController
public class RecipeController {
    @Autowired // This means to get the bean called CategoryRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    private RecipeRepository _recipeRepository;

    @Autowired
    private CookbookRepository _cookbookRepository;

    @Autowired
    private RecipeTagRepository _recipeTagRepository;

    @Autowired
    private HistoryItemRepository _historyItemRepository;

    @CrossOrigin
    @RequestMapping("/recipeSearch")
    public Set<Recipe> recipeSearch(@RequestBody SearchCriteria criteria) {
        System.out.println("recipeSearch() criteria.searchText = " + criteria.getSearchText()
                + ", criteria.tags.size = " + (criteria.getTags() != null ? criteria.getTags().size() : "null"));
        Set<Recipe> results = new HashSet<>();

        if (StringUtils.isNotBlank(criteria.getSearchText())) {
            List<Recipe> temp1 = _recipeRepository.findByRecipeNameIgnoreCaseContainingOrNotesIgnoreCaseContaining(
                    criteria.getSearchText(), criteria.getSearchText());

            if (CollectionUtils.isNotEmpty(temp1)) {
                results.addAll(temp1);
            }
        }

        if (CollectionUtils.isNotEmpty(criteria.getTags())) {
            List<Recipe> temp2 = _recipeRepository.findByRecipeTagsIn(criteria.getTags());
            results.addAll(temp2);
        }

        if (CollectionUtils.isNotEmpty(criteria.getCookbookIds())) {
            List<Recipe> temp3 = _recipeRepository.findByCookbookIdIn(criteria.getCookbookIds());
            results.addAll(temp3);
        }

        System.out.println("recipeSearch() results.size() = " + results.size());
        results.forEach((recipe) -> {
            System.out.println("recipeSearch() recipe = " + recipe.getId() + ": " + recipe.getRecipeName());
        });
        return results;
    }

    @CrossOrigin
    @RequestMapping("/getRecipe")
    public Recipe getRecipe(@RequestBody Long id) {
        Recipe recipe = _recipeRepository.findOne(id);
        System.out
                .println("getRecipe() id = " + id + ", recipe = " + (recipe != null ? recipe.toString() : "null"));

        return recipe;
    }

    @CrossOrigin
    @RequestMapping("/getRecipeWithHistory")
    public Recipe getRecipeWithHistory(@RequestBody Long id) {
        Recipe recipe = _recipeRepository.findOne(id);
        System.out.println("getRecipeWithHistory() id = " + id + ", recipe = "
                + (recipe != null ? recipe.toString() : "null"));

        // only creating history when getting 'withHistory',
        // otherwise retrieving the recipe is just for 'hovering'
        _historyItemRepository.save(new HistoryItem(id));

        return recipe;
    }

    @CrossOrigin
    @RequestMapping("/deleteRecipe")
    public boolean deleteRecipe(@RequestBody Long recipeId) {
        try {
            // delete tables with a foreign key reference
            _historyItemRepository.deleteByRecipeId(recipeId);
            //        _recipeTagRepository.deleteByRecipeId(recipeId);

            _recipeRepository.delete(recipeId);
            return true;
        } catch (Exception e) {
            System.out.println("deleteRecipe() Exception caught: e = " + e.getMessage());
            return false;
        }
    }

    @CrossOrigin
    @RequestMapping("/getRecipesForCategory")
    public List<Recipe> getRecipesForCategory(@RequestBody Long categoryId) {
        // TODO
        return null;
    }

    @CrossOrigin
    @RequestMapping("/saveRecipe")
    public Recipe saveRecipe(@RequestBody Recipe recipe) {
        System.out.println("saveRecipe() recipe = " + recipe);
        return _recipeRepository.save(recipe);
    }

    @CrossOrigin
    @RequestMapping("/createRecipe")
    public Recipe createRecipe(@RequestBody Recipe recipe) {
        System.out.println("saveRecipe() recipe = " + recipe);

        // the cookbook needs to be saved separately
        if (recipe.getCookbook() != null && recipe.getCookbook().isNew()) {
            recipe.setCookbook(_cookbookRepository.save(recipe.getCookbook()));
        }

        // The tags need to be saved separately
        if (CollectionUtils.isNotEmpty(recipe.getRecipeTags())) {
            Set<RecipeTag> updatedList = new HashSet<>();

            recipe.getRecipeTags().forEach((recipeTag) -> {
                if (recipeTag.isNew()) {
                    updatedList.add(_recipeTagRepository.save(recipeTag));
                } else {
                    updatedList.add(recipeTag);
                }
            });

            recipe.setRecipeTags(updatedList);
        }

        return _recipeRepository.save(recipe);
    }

    @CrossOrigin
    @RequestMapping("/getAllRecipeTags")
    public List<RecipeTag> getAllRecipeTags() {
        System.out.println("getAllRecipeTags()");
        List<RecipeTag> tags = new ArrayList<>();

        _recipeTagRepository.findAll().forEach(tags::add);
        System.out.println("getAllRecipeTags() tags.size() = " + tags.size());

        return tags;
    }

    @CrossOrigin
    @RequestMapping("/findAddedRecently")
    public List<Recipe> findAddedRecently(@RequestBody Long count) {
        System.out.println("findAddedRecently() count = " + count);
        List<Recipe> recipes = new ArrayList<>();

        _recipeRepository.findAddedRecently(count).forEach(recipes::add);
        System.out.println("findAddedRecently() recipes.size() = " + recipes.size());

        return recipes;
    }

    @CrossOrigin
    @RequestMapping("/findMostViewed")
    public List<Recipe> findMostViewed(@RequestBody Long count) {
        System.out.println("findMostViewed() count = " + count);
        List<Recipe> recipes = new ArrayList<>();

        List<Object[]> mostViewed = _historyItemRepository.findMostViewed(count);

        if (CollectionUtils.isNotEmpty(mostViewed)) {
            mostViewed.forEach((obj) -> {
                // findAll(List<Long>) does _not_ maintain the order of the list of ids
                //        _recipeRepository.findAll(recipeIds).forEach((temp) -> recipes.add(temp));
                recipes.add(_recipeRepository.findOne(((BigInteger) obj[0]).longValue()));
            });
        }

        System.out.println("findMostViewed() recipes.size() = " + recipes.size());

        return recipes;
    }
}