minor formatting cleanup

This commit is contained in:
Eugen Paraschiv 2019-01-27 14:25:36 +02:00
parent 8ccec9a413
commit 2e733c3867
18 changed files with 122 additions and 132 deletions

View File

@ -20,7 +20,7 @@ import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
// @PropertySource("persistence-h2.properties") // @PropertySource("persistence-h2.properties")
// @PropertySource("persistence-hsqldb.properties") // @PropertySource("persistence-hsqldb.properties")
// @PropertySource("persistence-derby.properties") // @PropertySource("persistence-derby.properties")
//@PropertySource("persistence-sqlite.properties") // @PropertySource("persistence-sqlite.properties")
public class DbConfig { public class DbConfig {
@Autowired @Autowired
@ -65,21 +65,23 @@ public class DbConfig {
@Configuration @Configuration
@Profile("h2") @Profile("h2")
@PropertySource("classpath:persistence-h2.properties") @PropertySource("classpath:persistence-h2.properties")
class H2Config {} class H2Config {
}
@Configuration @Configuration
@Profile("hsqldb") @Profile("hsqldb")
@PropertySource("classpath:persistence-hsqldb.properties") @PropertySource("classpath:persistence-hsqldb.properties")
class HsqldbConfig {} class HsqldbConfig {
}
@Configuration @Configuration
@Profile("derby") @Profile("derby")
@PropertySource("classpath:persistence-derby.properties") @PropertySource("classpath:persistence-derby.properties")
class DerbyConfig {} class DerbyConfig {
}
@Configuration @Configuration
@Profile("sqlite") @Profile("sqlite")
@PropertySource("classpath:persistence-sqlite.properties") @PropertySource("classpath:persistence-sqlite.properties")
class SqliteConfig {} class SqliteConfig {
}

View File

@ -11,11 +11,11 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
@EnableWebMvc @EnableWebMvc
public class MvcConfig implements WebMvcConfigurer { public class MvcConfig implements WebMvcConfigurer {
public MvcConfig(){ public MvcConfig() {
super(); super();
} }
@Override @Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable(); configurer.enable();
@ -27,7 +27,7 @@ public class MvcConfig implements WebMvcConfigurer {
} }
@Bean @Bean
BookEventHandler bookEventHandler(){ BookEventHandler bookEventHandler() {
return new BookEventHandler(); return new BookEventHandler();
} }

View File

@ -12,10 +12,9 @@ import org.springframework.http.HttpMethod;
public class RestConfig implements RepositoryRestConfigurer { public class RestConfig implements RepositoryRestConfigurer {
@Override @Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration){ public void configureRepositoryRestConfiguration(RepositoryRestConfiguration repositoryRestConfiguration) {
repositoryRestConfiguration.getProjectionConfiguration().addProjection(CustomBook.class); repositoryRestConfiguration.getProjectionConfiguration().addProjection(CustomBook.class);
ExposureConfiguration config = repositoryRestConfiguration.getExposureConfiguration(); ExposureConfiguration config = repositoryRestConfiguration.getExposureConfiguration();
config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) -> config.forDomainType(WebsiteUser.class).withItemExposure((metadata, httpMethods) -> httpMethods.disable(HttpMethod.PATCH));
httpMethods.disable(HttpMethod.PATCH));
} }
} }

View File

@ -24,13 +24,7 @@ public class ValidatorEventRegister implements InitializingBean {
List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete"); List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete");
for (Map.Entry<String, Validator> entry : validators.entrySet()) { for (Map.Entry<String, Validator> entry : validators.entrySet()) {
events events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
.stream()
.filter(p -> entry
.getKey()
.startsWith(p))
.findFirst()
.ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
} }
} }
} }

View File

@ -8,33 +8,34 @@ import java.util.logging.Logger;
@RepositoryEventHandler @RepositoryEventHandler
public class AuthorEventHandler { public class AuthorEventHandler {
Logger logger = Logger.getLogger("Class AuthorEventHandler"); Logger logger = Logger.getLogger("Class AuthorEventHandler");
public AuthorEventHandler(){
super();
}
@HandleBeforeCreate public AuthorEventHandler() {
public void handleAuthorBeforeCreate(Author author){ super();
logger.info("Inside Author Before Create...."); }
String name = author.getName();
}
@HandleAfterCreate @HandleBeforeCreate
public void handleAuthorAfterCreate(Author author){ public void handleAuthorBeforeCreate(Author author) {
logger.info("Inside Author After Create ...."); logger.info("Inside Author Before Create....");
String name = author.getName(); String name = author.getName();
} }
@HandleBeforeDelete @HandleAfterCreate
public void handleAuthorBeforeDelete(Author author){ public void handleAuthorAfterCreate(Author author) {
logger.info("Inside Author Before Delete ...."); logger.info("Inside Author After Create ....");
String name = author.getName(); String name = author.getName();
} }
@HandleAfterDelete @HandleBeforeDelete
public void handleAuthorAfterDelete(Author author){ public void handleAuthorBeforeDelete(Author author) {
logger.info("Inside Author After Delete ...."); logger.info("Inside Author Before Delete ....");
String name = author.getName(); String name = author.getName();
} }
@HandleAfterDelete
public void handleAuthorAfterDelete(Author author) {
logger.info("Inside Author After Delete ....");
String name = author.getName();
}
} }

View File

@ -10,17 +10,18 @@ import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
@RepositoryEventHandler @RepositoryEventHandler
public class BookEventHandler { public class BookEventHandler {
Logger logger = Logger.getLogger("Class BookEventHandler"); Logger logger = Logger.getLogger("Class BookEventHandler");
@HandleBeforeCreate
public void handleBookBeforeCreate(Book book){
logger.info("Inside Book Before Create ...."); @HandleBeforeCreate
book.getAuthors(); public void handleBookBeforeCreate(Book book) {
}
@HandleBeforeCreate logger.info("Inside Book Before Create ....");
public void handleAuthorBeforeCreate(Author author){ book.getAuthors();
logger.info("Inside Author Before Create ...."); }
author.getBooks();
} @HandleBeforeCreate
public void handleAuthorBeforeCreate(Author author) {
logger.info("Inside Author Before Create ....");
author.getBooks();
}
} }

View File

@ -19,12 +19,7 @@ public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionH
public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) { public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex; RepositoryConstraintViolationException nevEx = (RepositoryConstraintViolationException) ex;
String errors = nevEx String errors = nevEx.getErrors().getAllErrors().stream().map(ObjectError::toString).collect(Collectors.joining("\n"));
.getErrors()
.getAllErrors()
.stream()
.map(ObjectError::toString)
.collect(Collectors.joining("\n"));
return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE); return new ResponseEntity<>(errors, new HttpHeaders(), HttpStatus.NOT_ACCEPTABLE);
} }

View File

@ -11,7 +11,7 @@ import javax.persistence.OneToOne;
public class Address { public class Address {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)

View File

@ -16,7 +16,7 @@ import javax.persistence.ManyToMany;
public class Author { public class Author {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)

View File

@ -16,14 +16,14 @@ import javax.persistence.ManyToOne;
public class Book { public class Book {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)
private String title; private String title;
private String isbn; private String isbn;
@ManyToOne @ManyToOne
@JoinColumn(name = "library_id") @JoinColumn(name = "library_id")
private Library library; private Library library;
@ -63,7 +63,6 @@ public class Book {
this.isbn = isbn; this.isbn = isbn;
} }
public Library getLibrary() { public Library getLibrary() {
return library; return library;
} }

View File

@ -17,7 +17,7 @@ import org.springframework.data.rest.core.annotation.RestResource;
public class Library { public class Library {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
@Column @Column

View File

@ -10,7 +10,7 @@ import javax.persistence.Id;
public class Subject { public class Subject {
@Id @Id
@GeneratedValue(strategy=GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)

View File

@ -8,15 +8,15 @@ import org.springframework.data.rest.core.config.Projection;
import com.baeldung.models.Author; import com.baeldung.models.Author;
import com.baeldung.models.Book; import com.baeldung.models.Book;
@Projection(name = "customBook", types = { Book.class }) @Projection(name = "customBook", types = { Book.class })
public interface CustomBook { public interface CustomBook {
@Value("#{target.id}") @Value("#{target.id}")
long getId(); long getId();
String getTitle(); String getTitle();
List<Author> getAuthors(); List<Author> getAuthors();
@Value("#{target.getAuthors().size()}") @Value("#{target.getAuthors().size()}")
int getAuthorCount(); int getAuthorCount();
} }

View File

@ -7,4 +7,5 @@ import com.baeldung.models.Book;
import com.baeldung.projections.CustomBook; import com.baeldung.projections.CustomBook;
@RepositoryRestResource(excerptProjection = CustomBook.class) @RepositoryRestResource(excerptProjection = CustomBook.class)
public interface BookRepository extends CrudRepository<Book, Long> {} public interface BookRepository extends CrudRepository<Book, Long> {
}

View File

@ -8,8 +8,8 @@ import org.springframework.data.rest.core.annotation.RestResource;
import com.baeldung.models.Subject; import com.baeldung.models.Subject;
public interface SubjectRepository extends PagingAndSortingRepository<Subject, Long> { public interface SubjectRepository extends PagingAndSortingRepository<Subject, Long> {
@RestResource(path = "nameContains") @RestResource(path = "nameContains")
public Page<Subject> findByNameContaining(@Param("name") String name, Pageable p); public Page<Subject> findByNameContaining(@Param("name") String name, Pageable p);
} }

View File

@ -9,21 +9,21 @@ import static org.mockito.Mockito.mock;
public class AuthorEventHandlerUnitTest { public class AuthorEventHandlerUnitTest {
@Test @Test
public void whenCreateAuthorThenSuccess() { public void whenCreateAuthorThenSuccess() {
Author author = mock(Author.class); Author author = mock(Author.class);
AuthorEventHandler authorEventHandler = new AuthorEventHandler(); AuthorEventHandler authorEventHandler = new AuthorEventHandler();
authorEventHandler.handleAuthorBeforeCreate(author); authorEventHandler.handleAuthorBeforeCreate(author);
Mockito.verify(author,Mockito.times(1)).getName(); Mockito.verify(author, Mockito.times(1)).getName();
} }
@Test @Test
public void whenDeleteAuthorThenSuccess() { public void whenDeleteAuthorThenSuccess() {
Author author = mock(Author.class); Author author = mock(Author.class);
AuthorEventHandler authorEventHandler = new AuthorEventHandler(); AuthorEventHandler authorEventHandler = new AuthorEventHandler();
authorEventHandler.handleAuthorAfterDelete(author); authorEventHandler.handleAuthorAfterDelete(author);
Mockito.verify(author,Mockito.times(1)).getName(); Mockito.verify(author, Mockito.times(1)).getName();
} }
} }

View File

@ -8,21 +8,21 @@ import org.mockito.Mockito;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
public class BookEventHandlerUnitTest { public class BookEventHandlerUnitTest {
@Test @Test
public void whenCreateBookThenSuccess() { public void whenCreateBookThenSuccess() {
Book book = mock(Book.class); Book book = mock(Book.class);
BookEventHandler bookEventHandler = new BookEventHandler(); BookEventHandler bookEventHandler = new BookEventHandler();
bookEventHandler.handleBookBeforeCreate(book); bookEventHandler.handleBookBeforeCreate(book);
Mockito.verify(book,Mockito.times(1)).getAuthors(); Mockito.verify(book, Mockito.times(1)).getAuthors();
} }
@Test @Test
public void whenCreateAuthorThenSuccess() { public void whenCreateAuthorThenSuccess() {
Author author = mock(Author.class); Author author = mock(Author.class);
BookEventHandler bookEventHandler = new BookEventHandler(); BookEventHandler bookEventHandler = new BookEventHandler();
bookEventHandler.handleAuthorBeforeCreate(author); bookEventHandler.handleAuthorBeforeCreate(author);
Mockito.verify(author,Mockito.times(1)).getBooks(); Mockito.verify(author, Mockito.times(1)).getBooks();
} }
} }

View File

@ -29,16 +29,15 @@ public class SpringDataProjectionLiveTest {
private static final String BOOK_ENDPOINT = "http://localhost:8080/books"; private static final String BOOK_ENDPOINT = "http://localhost:8080/books";
private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors"; private static final String AUTHOR_ENDPOINT = "http://localhost:8080/authors";
@Autowired @Autowired
private BookRepository bookRepo; private BookRepository bookRepo;
@Autowired @Autowired
private AuthorRepository authorRepo; private AuthorRepository authorRepo;
@Before @Before
public void setup(){ public void setup() {
if(bookRepo.findById(1L) == null){ if (bookRepo.findById(1L) == null) {
Book book = new Book("Animal Farm"); Book book = new Book("Animal Farm");
book.setIsbn("978-1943138425"); book.setIsbn("978-1943138425");
book = bookRepo.save(book); book = bookRepo.save(book);
@ -48,45 +47,44 @@ public class SpringDataProjectionLiveTest {
author = authorRepo.save(author); author = authorRepo.save(author);
} }
} }
@Test @Test
public void whenGetBook_thenOK(){ public void whenGetBook_thenOK() {
final Response response = RestAssured.get(BOOK_ENDPOINT+"/1"); final Response response = RestAssured.get(BOOK_ENDPOINT + "/1");
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
assertTrue(response.asString().contains("isbn")); assertTrue(response.asString().contains("isbn"));
assertFalse(response.asString().contains("authorCount")); assertFalse(response.asString().contains("authorCount"));
// System.out.println(response.asString()); // System.out.println(response.asString());
} }
@Test @Test
public void whenGetBookProjection_thenOK(){ public void whenGetBookProjection_thenOK() {
final Response response = RestAssured.get(BOOK_ENDPOINT+"/1?projection=customBook"); final Response response = RestAssured.get(BOOK_ENDPOINT + "/1?projection=customBook");
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
assertFalse(response.asString().contains("isbn")); assertFalse(response.asString().contains("isbn"));
assertTrue(response.asString().contains("authorCount")); assertTrue(response.asString().contains("authorCount"));
// System.out.println(response.asString()); // System.out.println(response.asString());
} }
@Test @Test
public void whenGetAllBooks_thenOK(){ public void whenGetAllBooks_thenOK() {
final Response response = RestAssured.get(BOOK_ENDPOINT); final Response response = RestAssured.get(BOOK_ENDPOINT);
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
assertFalse(response.asString().contains("isbn")); assertFalse(response.asString().contains("isbn"));
assertTrue(response.asString().contains("authorCount")); assertTrue(response.asString().contains("authorCount"));
// System.out.println(response.asString()); // System.out.println(response.asString());
} }
@Test @Test
public void whenGetAuthorBooks_thenOK(){ public void whenGetAuthorBooks_thenOK() {
final Response response = RestAssured.get(AUTHOR_ENDPOINT+"/1/books"); final Response response = RestAssured.get(AUTHOR_ENDPOINT + "/1/books");
assertEquals(200, response.getStatusCode()); assertEquals(200, response.getStatusCode());
assertFalse(response.asString().contains("isbn")); assertFalse(response.asString().contains("isbn"));
assertTrue(response.asString().contains("authorCount")); assertTrue(response.asString().contains("authorCount"));
System.out.println(response.asString()); System.out.println(response.asString());
} }
} }