Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit aa09add

Browse files
[dev + improve] Refactored and improved the complete project
1 parent 1152523 commit aa09add

File tree

13 files changed

+187
-298
lines changed

13 files changed

+187
-298
lines changed

‎d04/d04s06-complete-project/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@
1414
<version>1.0-SNAPSHOT</version>
1515

1616
<dependencies>
17+
<dependency>
18+
<groupId>com.h2database</groupId>
19+
<artifactId>h2</artifactId>
20+
</dependency>
21+
1722
<dependency>
1823
<groupId>com.zaxxer</groupId>
1924
<artifactId>HikariCP</artifactId>

‎d04/d04s06-complete-project/src/main/java/net/safedata/spring/training/complete/project/ProductService.java

Lines changed: 0 additions & 92 deletions
This file was deleted.

‎d04/d04s06-complete-project/src/main/java/net/safedata/spring/training/complete/project/config/DataSourceConfig.java

Lines changed: 0 additions & 58 deletions
This file was deleted.

‎d04/d04s06-complete-project/src/main/java/net/safedata/spring/training/complete/project/config/SecurityConfiguration.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
4242
@Autowired
4343
public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
4444
auth.inMemoryAuthentication()
45-
//.passwordEncoder(passwordEncoder())
45+
.passwordEncoder(passwordEncoder())
4646
.withUser("user")
47-
.password("password")
47+
// the unencrypted password is 'password'
48+
.password("2ドルa10ドル4ドルxnpk2a5jLr1mf6VWle6Vuv4q7DBsW2rqQcg6N1Ms/y4g98Ry4D4C")
4849
.roles("USER");
4950
}
5051

@@ -53,8 +54,8 @@ protected void configure(final HttpSecurity http) throws Exception {
5354
http.authorizeRequests()
5455
.antMatchers("/resources/static/**", "/about").permitAll()
5556
.antMatchers(HttpMethod.POST, "/admin").hasAnyRole("ADMIN")
56-
.antMatchers(HttpMethod.GET, "/product").fullyAuthenticated()
57-
.antMatchers(HttpMethod.POST, "/product").hasAuthority("WRITE")
57+
.antMatchers(HttpMethod.GET, "/product/**").permitAll()
58+
.antMatchers(HttpMethod.POST, "/product/**").permitAll()
5859
.anyRequest().authenticated();
5960

6061
// registering the post auth handlers
Lines changed: 50 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,19 @@
11
package net.safedata.spring.training.complete.project.controller;
22

3-
import net.safedata.spring.training.complete.project.dto.ProductDTO;
43
import net.safedata.spring.training.complete.project.model.Product;
5-
import net.safedata.spring.training.complete.project.security.auth.HasManagerRole;
6-
import net.safedata.spring.training.complete.project.ProductService;
4+
import net.safedata.spring.training.complete.project.service.ProductService;
75
import org.springframework.beans.factory.annotation.Autowired;
86
import org.springframework.http.HttpStatus;
9-
import org.springframework.http.MediaType;
107
import org.springframework.http.ResponseEntity;
11-
import org.springframework.security.access.annotation.Secured;
12-
import org.springframework.security.access.prepost.PreAuthorize;
13-
import org.springframework.security.core.Authentication;
14-
import org.springframework.security.core.annotation.AuthenticationPrincipal;
15-
import org.springframework.security.core.userdetails.UserDetails;
8+
import org.springframework.web.bind.annotation.DeleteMapping;
169
import org.springframework.web.bind.annotation.GetMapping;
1710
import org.springframework.web.bind.annotation.PathVariable;
11+
import org.springframework.web.bind.annotation.PostMapping;
12+
import org.springframework.web.bind.annotation.PutMapping;
1813
import org.springframework.web.bind.annotation.RequestBody;
1914
import org.springframework.web.bind.annotation.RequestMapping;
20-
import org.springframework.web.bind.annotation.RequestMethod;
2115
import org.springframework.web.bind.annotation.RestController;
2216

23-
import javax.servlet.http.HttpServletRequest;
24-
import javax.servlet.http.HttpServletResponse;
25-
import javax.validation.Valid;
26-
import java.security.Principal;
27-
import java.util.List;
28-
29-
import static net.safedata.spring.training.complete.project.security.auth.Roles.ADMIN_ROLE;
30-
3117
/**
3218
* A Spring {@link RestController} used to showcase the modeling of a REST controller for CRUD operations
3319
*
@@ -37,7 +23,6 @@
3723
@RequestMapping(
3824
path = "/product"
3925
)
40-
// TODO integrate Swagger REST API generation
4126
public class ProductController {
4227

4328
private final ProductService productService;
@@ -47,86 +32,65 @@ public ProductController(final ProductService productService) {
4732
this.productService = productService;
4833
}
4934

50-
@RequestMapping(
51-
method = RequestMethod.POST,
52-
path = "",
53-
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE
54-
)
55-
public ResponseEntity<?> create(@RequestBody @Valid ProductDTO productDTO) {
56-
productService.create(productDTO);
35+
/**
36+
* Creates the referenced {@link Product}
37+
*
38+
* @param product the {@link Product} to be created
39+
*
40+
* @return a {@link ResponseEntity} with the appropriate {@link HttpStatus}
41+
*/
42+
@PostMapping("")
43+
public ResponseEntity create(@RequestBody Product product) {
44+
productService.create(product);
5745
return ResponseEntity.ok(HttpStatus.OK);
5846
}
5947

60-
@RequestMapping(
61-
method = RequestMethod.GET,
62-
path = "/{id}",
63-
produces = MediaType.APPLICATION_JSON_UTF8_VALUE
64-
)
65-
public ProductDTO getProduct(@PathVariable final int id) {
48+
/**
49+
* Reads the {@link Product} with the specified id
50+
*
51+
* @param id the id of the requested {@link Product}
52+
*
53+
* @return the serialized {@link Product}
54+
*/
55+
@GetMapping("/{id}")
56+
public Product getProduct(@PathVariable final int id) {
6657
return productService.get(id);
6758
}
6859

69-
@RequestMapping(
70-
method = RequestMethod.GET,
71-
path = ""
72-
)
73-
public List<ProductDTO> getAll() {
60+
/**
61+
* Reads all the existing {@link Product}s
62+
*
63+
* @return the serialized {@link Product}s
64+
*/
65+
@GetMapping("")
66+
public Iterable<Product> getAll() {
7467
return productService.getAll();
7568
}
7669

77-
@RequestMapping(
78-
method = RequestMethod.PUT,
79-
path = "/{id}"
80-
)
81-
public ResponseEntity<?> update(@PathVariable final int id, @RequestBody ProductDTO productDTO) {
82-
productService.update(id, productDTO);
70+
/**
71+
* Updates the {@link Product} with the specified ID with the details from the referenced {@link Product}
72+
*
73+
* @param id the ID of the updated {@link Product}
74+
* @param product the new {@link Product} details
75+
*
76+
* @return a {@link ResponseEntity} with the appropriate {@link HttpStatus}
77+
*/
78+
@PutMapping("/{id}")
79+
public ResponseEntity update(@PathVariable final int id, @RequestBody Product product) {
80+
productService.update(id, product);
8381
return ResponseEntity.ok(HttpStatus.OK);
8482
}
8583

86-
@RequestMapping(
87-
method = RequestMethod.DELETE,
88-
path = "/{id}"
89-
)
90-
public ResponseEntity<?> delete(@PathVariable final int id) {
84+
/**
85+
* Deletes the {@link Product} with the specified ID
86+
*
87+
* @param id the ID of the deleted {@link Product}
88+
*
89+
* @return a {@link ResponseEntity} with the appropriate {@link HttpStatus}
90+
*/
91+
@DeleteMapping(path = "/{id}")
92+
public ResponseEntity delete(@PathVariable final int id) {
9193
productService.delete(id);
9294
return ResponseEntity.ok(HttpStatus.OK);
9395
}
94-
95-
// -------------------------------------------------------------------------
96-
@PreAuthorize("hasRole('" + ADMIN_ROLE + "') AND hasAuthority('WRITE')")
97-
public void addProduct(final Authentication authentication) {
98-
// further use the Authentication object, if needed
99-
}
100-
101-
@GetMapping(
102-
path = "/product/{id}"
103-
)
104-
public Product getProduct(@PathVariable final int id, final @AuthenticationPrincipal UserDetails userDetails) {
105-
final String username = userDetails.getUsername();
106-
System.out.println("The current user is '" + username + "'");
107-
return new Product(20, "Tablet");
108-
}
109-
110-
// dynamically retrieving the authenticated user details
111-
public void passAuthenticatedUser(final @AuthenticationPrincipal UserDetails userDetails) {
112-
/* the same details can be obtained using:
113-
final SecurityContext securityContext = SecurityContextHolder.getContext();
114-
final UserDetails details = (UserDetails) securityContext.getAuthentication().getPrincipal();
115-
*/
116-
117-
final String username = userDetails.getUsername();
118-
// the user details can be further passed to the services
119-
}
120-
121-
@Secured("ROLE_ADMIN")
122-
public void processRequestOrResponseParameters(final HttpServletRequest request, final HttpServletResponse response) {
123-
// get parameters from the HTTP request, set details in the response
124-
}
125-
126-
// recommended to be used when the principal details need to be consumed by an external tool / API
127-
@GetMapping("/currentUser")
128-
@HasManagerRole // DRY
129-
public Principal principal(final Principal principal) {
130-
return principal;
131-
}
13296
}

‎d04/d04s06-complete-project/src/main/java/net/safedata/spring/training/complete/project/errorhandling/ExceptionHandlers.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,10 +32,7 @@ public MessageDTO illegalArgumentException(final IllegalArgumentException e) {
3232
return new MessageDTO(e.getMessage());
3333
}
3434

35-
@ExceptionHandler({
36-
AccessDeniedException.class,
37-
IllegalArgumentException.class
38-
})
35+
@ExceptionHandler(AccessDeniedException.class)
3936
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
4037
public MessageDTO unauthorized() {
4138
return new MessageDTO("Unauthorized access");

‎d04/d04s06-complete-project/src/main/java/net/safedata/spring/training/complete/project/model/Product.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
package net.safedata.spring.training.complete.project.model;
22

3+
import javax.persistence.Entity;
4+
import javax.persistence.GeneratedValue;
5+
import javax.persistence.GenerationType;
6+
import javax.persistence.Id;
37
import java.io.Serializable;
48
import java.util.Objects;
59

10+
@Entity
611
public class Product implements Serializable {
7-
8-
private static final long serialVersionUID = 1L;
912

13+
@Id
14+
@GeneratedValue(strategy = GenerationType.AUTO)
1015
private int id;
1116

1217
private String name;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /