com.tamnd2.basicwebapp.rest.mvc.AccountController.java Source code

Java tutorial

Introduction

Here is the source code for com.tamnd2.basicwebapp.rest.mvc.AccountController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tamnd2.basicwebapp.rest.mvc;

import com.tamnd2.basicwebapp.core.entities.Account;
import com.tamnd2.basicwebapp.core.entities.Blog;
import com.tamnd2.basicwebapp.core.services.AccountService;
import com.tamnd2.basicwebapp.core.services.exceptions.AccountDoesNotExistException;
import com.tamnd2.basicwebapp.core.services.exceptions.AccountExistException;
import com.tamnd2.basicwebapp.core.services.exceptions.BlogExistException;
import com.tamnd2.basicwebapp.core.services.util.AccountList;
import com.tamnd2.basicwebapp.core.services.util.BlogList;
import com.tamnd2.basicwebapp.rest.exceptions.ConflictException;
import com.tamnd2.basicwebapp.rest.exceptions.ForbiddenException;
import com.tamnd2.basicwebapp.rest.exceptions.NotFoundException;
import com.tamnd2.basicwebapp.rest.resources.AccountListResource;
import com.tamnd2.basicwebapp.rest.resources.AccountResource;
import com.tamnd2.basicwebapp.rest.resources.BlogListResource;
import com.tamnd2.basicwebapp.rest.resources.BlogResource;
import com.tamnd2.basicwebapp.rest.resources.asm.AccountListResourceAsm;
import com.tamnd2.basicwebapp.rest.resources.asm.AccountResourceAsm;
import com.tamnd2.basicwebapp.rest.resources.asm.BlogListResourceAsm;
import com.tamnd2.basicwebapp.rest.resources.asm.BlogResourceAsm;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 *
 * @author tamnd2
 */
@Controller
@RequestMapping("/rest/accounts")
public class AccountController {

    private final AccountService accountService;

    @Autowired
    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @RequestMapping(method = RequestMethod.GET)
    @PreAuthorize("permitAll")
    public ResponseEntity<AccountListResource> findAllAccounts(
            @RequestParam(value = "name", required = false) String name) {
        AccountList list = null;
        if (name == null) {
            list = accountService.findAllAccounts();
        } else {
            Account account = accountService.findByAccountName(name);
            if (account == null) {
                list = new AccountList(new ArrayList<Account>());
            } else {
                list = new AccountList(Arrays.asList(account));
            }
        }
        AccountListResource res = new AccountListResourceAsm().toResource(list);
        return new ResponseEntity<AccountListResource>(res, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST)
    @PreAuthorize("permitAll")
    public ResponseEntity<AccountResource> createAccount(@RequestBody AccountResource sentAccount) {
        try {
            Account createdAccount = accountService.createAccount(sentAccount.toAccount());
            AccountResource res = new AccountResourceAsm().toResource(createdAccount);
            HttpHeaders headers = new HttpHeaders();
            headers.setLocation(URI.create(res.getLink("self").getHref()));
            return new ResponseEntity<AccountResource>(res, headers, HttpStatus.CREATED);
        } catch (AccountExistException exception) {
            throw new ConflictException(exception);
        }
    }

    @RequestMapping(value = "/{accountId}", method = RequestMethod.GET)
    @PreAuthorize("permitAll")
    public ResponseEntity<AccountResource> getAccount(@PathVariable Long accountId) {
        Account account = accountService.findAccount(accountId);
        if (account != null) {
            AccountResource res = new AccountResourceAsm().toResource(account);
            return new ResponseEntity<AccountResource>(res, HttpStatus.OK);
        } else {
            return new ResponseEntity<AccountResource>(HttpStatus.NOT_FOUND);
        }
    }

    @RequestMapping(value = "/{accountId}/blogs", method = RequestMethod.POST)
    @PreAuthorize("permitAll")
    public ResponseEntity<BlogResource> createBlog(@PathVariable Long accountId, @RequestBody BlogResource res) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            UserDetails details = (UserDetails) principal;
            Account loggedIn = accountService.findByAccountName(details.getUsername());
            if (loggedIn.getId().equals(accountId)) {
                try {
                    Blog createdBlog = accountService.createBlog(accountId, res.toBlog());
                    BlogResource createdBlogRes = new BlogResourceAsm().toResource(createdBlog);
                    HttpHeaders headers = new HttpHeaders();
                    headers.setLocation(URI.create(createdBlogRes.getLink("self").getHref()));
                    return new ResponseEntity<BlogResource>(createdBlogRes, headers, HttpStatus.CREATED);
                } catch (AccountDoesNotExistException exception) {
                    throw new NotFoundException(exception);
                } catch (BlogExistException exception) {
                    throw new ConflictException(exception);
                }
            } else {
                throw new ForbiddenException();
            }
        } else {
            throw new ForbiddenException();
        }
    }

    @RequestMapping(value = "/{accountId}/blogs", method = RequestMethod.GET)
    @PreAuthorize("permitAll")
    public ResponseEntity<BlogListResource> findAllBlogs(@PathVariable Long accountId) {
        try {
            BlogList blogList = accountService.findBlogsByAccount(accountId);
            BlogListResource blogListRes = new BlogListResourceAsm().toResource(blogList);
            return new ResponseEntity<BlogListResource>(blogListRes, HttpStatus.OK);
        } catch (AccountDoesNotExistException exception) {
            throw new NotFoundException(exception);
        }
    }
}