Skip to content

Michael cavellier1 #19

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Java Frameworks Sprint Challenge

//test for codegrade
**Read these instructions carefully. Understand exactly what is expected _before_ starting this Sprint Challenge.**

This challenge allows you to practice the concepts and techniques learned over the past sprint and apply them in a concrete project. This sprint explored **using Frameworks in Java**. During this sprint, you studied **Exception Handling, User Authentication, Automated Testing, and Deployment**. In your challenge this week, you will demonstrate your mastery of these skills by creating **a Java Spring REST API Application**.
Expand All @@ -12,7 +12,7 @@ _You have **three hours** to complete this challenge. Plan your time accordingly

## Introduction

This is a basic bookstore database scheme with books that have authors. Books may have many authors and many authors may have written many books. The relationship between books and authors is called `wrote`. Each book can be found in only one section of the bookstore.
This is a basic bookstore database scheme with books that have authors. Books may have many authors and many authors may have written many books. The relationship between books and authors is called `wrote`. Each book can be found in only one section of the bookstore.

### Commits

Expand Down
20 changes: 20 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@
</properties>

<dependencies>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
Expand Down Expand Up @@ -100,6 +104,22 @@

<build>
<plugins>
<plugin>
<groupId>com.heroku.sdk</groupId>
<artifactId>heroku-maven-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<appName>${project.build.finalName}</appName>
<includeTarget>false</includeTarget>
<includes>
<include>${project.build.directory}/${project.build.finalName}.jar</include>
</includes>
<jdkVersion>${java.version}</jdkVersion>
<processTypes>
<web>java $JAVA_OPTS -Dserver.port=$PORT -jar target/${project.build.finalName}.jar</web>
</processTypes>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ public void configure(HttpSecurity http)
"/oauth/revoke-token",
"/logout")
.authenticated()
.antMatchers("/books/books",
"/books/book/**")
.hasAnyRole("ADMIN", "DATA", "USER")
.antMatchers("/roles/**")
.hasAnyRole("ADMIN", "DATA")
.anyRequest().denyAll()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
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.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand Down Expand Up @@ -52,6 +53,7 @@ public ResponseEntity<?> getBookById(HttpServletRequest request,
}

// POST http://localhost:2019/books/book
@PreAuthorize("hasAnyRole('ADMIN')")
@PostMapping(value = "/book", consumes = "application/json")
public ResponseEntity<?> addNewBook(@Valid @RequestBody Book newBook) throws
URISyntaxException
Expand All @@ -73,6 +75,7 @@ public ResponseEntity<?> addNewBook(@Valid @RequestBody Book newBook) throws
}

// PUT http://localhost:2019/books/book/1
@PreAuthorize("hasAnyRole('ADMIN')")
@PutMapping(value = "/book/{bookid}",
consumes = "application/json")
public ResponseEntity<?> updateFullBook(
Expand All @@ -89,6 +92,7 @@ public ResponseEntity<?> updateFullBook(
}

// DELETE http://localhost:2019/books/book/1
@PreAuthorize("hasAnyRole('ADMIN')")
@DeleteMapping(value = "/book/{id}")
public ResponseEntity<?> deleteBookById(
@PathVariable
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lambdaschool.bookstore.services;

import com.lambdaschool.bookstore.exceptions.ResourceNotFoundException;
import com.lambdaschool.bookstore.models.Author;
import com.lambdaschool.bookstore.models.Book;
import com.lambdaschool.bookstore.models.Wrote;
Expand Down Expand Up @@ -45,7 +46,7 @@ public List<Book> findAll()
public Book findBookById(long id)
{
return bookrepos.findById(id)
.orElseThrow(() -> new EntityNotFoundException("Book with id " + id + " Not Found!"));
.orElseThrow(() -> new ResourceNotFoundException("Book with id " + id + " Not Found!"));
}

@Transactional
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#local.run.db=H2
local.run.db=POSTGRESQL
# Configurations useful for working with H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.lambdaschool.bookstore.controllers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lambdaschool.bookstore.BookstoreApplicationTest;
import com.lambdaschool.bookstore.models.Author;
import com.lambdaschool.bookstore.models.Book;
Expand All @@ -8,23 +9,34 @@
import com.lambdaschool.bookstore.services.BookService;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WithMockUser(username = "admin", roles = {"ADMIN", "DATA"})
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = BookstoreApplicationTest.class)
@AutoConfigureMockMvc
Expand Down Expand Up @@ -124,18 +136,47 @@ public void tearDown() throws
public void listAllBooks() throws
Exception
{

String apiURL = "/books/books";
Mockito.when(bookService.findAll()).thenReturn(myBookList);
RequestBuilder rb = MockMvcRequestBuilders.get(apiURL).accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb).andReturn();
String tr = r.getResponse().getContentAsString();
ObjectMapper mapper = new ObjectMapper();
String er = mapper.writeValueAsString(myBookList);
Assert.assertEquals(er, tr);

}

@Test
public void getBookById() throws
Exception
{

String apiURL = "/books/book/1/";
Mockito.when(bookService.findBookById(1)).thenReturn(myBookList.get(0));
RequestBuilder rb = MockMvcRequestBuilders.get(apiURL).accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb).andReturn();
String tr = r.getResponse().getContentAsString();
ObjectMapper mapper = new ObjectMapper();
String er = mapper.writeValueAsString(myBookList.get(0));
Assert.assertEquals(er,tr);

}

@Test
public void getNoBookById() throws
Exception
{

String apiUrl = "/books/book/198";
Mockito.when(bookService.findBookById(1000)).thenReturn(null);
RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl).accept(MediaType.APPLICATION_JSON);
MvcResult r = mockMvc.perform(rb).andReturn();
String tr = r.getResponse().getContentAsString();
String er = "";
Assert.assertEquals(er, tr);

}

@Test
Expand All @@ -153,5 +194,10 @@ public void updateFullBook()
public void deleteBookById() throws
Exception
{

String apiUrl = "/books/book/{bookid}";
RequestBuilder rb = MockMvcRequestBuilders.delete(apiUrl, 1).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
mockMvc.perform(rb).andExpect(status().isOk()).andDo(MockMvcResultHandlers.print());

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static junit.framework.TestCase.assertEquals;

Expand Down Expand Up @@ -115,21 +116,39 @@ public void tearDown() throws
@Test
public void findAll()
{

Mockito.when((bookrepos.findAll())).thenReturn(myBookList);
assertEquals(5, bookService.findAll().size());

}

@Test
public void findBookById()
{

Mockito.when(bookrepos.findById(2L)).thenReturn(Optional.of(myBookList.get(0)));
assertEquals("Flatterland", bookService.findBookById(2).getTitle());

}

@Test(expected = ResourceNotFoundException.class)
public void notFindBookById()
{

Mockito.when(bookrepos.findById(1000L)).thenThrow(ResourceNotFoundException.class);
assertEquals("Flatterland", bookService.findBookById(1000).getTitle());

}

@Test
public void delete()
{

Mockito.when(bookrepos.findById(2L)).thenReturn(Optional.of(myBookList.get(0)));
Mockito.doNothing().when(bookrepos).deleteById(2L);
bookService.delete(2);
assertEquals(5, myBookList.size());

}

@Test
Expand Down
2 changes: 2 additions & 0 deletions target/classes/application.properties
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#local.run.db=H2
local.run.db=POSTGRESQL
# Configurations useful for working with H2
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
Expand Down