Skip to content

Commit 84e1d64

Browse files
committed
Swagger improves
1 parent 0b370c8 commit 84e1d64

File tree

17 files changed

+365
-325
lines changed

17 files changed

+365
-325
lines changed

pom.xml

Lines changed: 209 additions & 198 deletions
Large diffs are not rendered by default.
Lines changed: 54 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,99 @@
11
package com.github.throyer.common.springboot.configurations;
22

3-
import java.util.Arrays;
4-
import java.util.Collections;
3+
import static java.util.Arrays.asList;
4+
import static java.util.Collections.emptyList;
5+
import static springfox.documentation.builders.PathSelectors.any;
6+
import static springfox.documentation.builders.RequestHandlerSelectors.basePackage;
7+
import static springfox.documentation.spi.DocumentationType.OAS_30;
8+
59
import java.util.List;
610

11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.boot.info.BuildProperties;
713
import org.springframework.context.annotation.Bean;
814
import org.springframework.context.annotation.Configuration;
15+
import org.springframework.http.HttpMethod;
16+
import org.springframework.stereotype.Component;
17+
import springfox.documentation.builders.ResponseBuilder;
18+
import springfox.documentation.builders.ResponseMessageBuilder;
919

10-
import springfox.documentation.builders.PathSelectors;
11-
import springfox.documentation.builders.RequestHandlerSelectors;
1220
import springfox.documentation.service.ApiInfo;
1321
import springfox.documentation.service.ApiKey;
1422
import springfox.documentation.service.AuthorizationScope;
1523
import springfox.documentation.service.Contact;
1624
import springfox.documentation.service.SecurityReference;
17-
import springfox.documentation.spi.DocumentationType;
1825
import springfox.documentation.spi.service.contexts.SecurityContext;
1926
import springfox.documentation.spring.web.plugins.Docket;
2027

28+
@Component
2129
@Configuration
2230
public class SwaggerConfiguration {
2331

32+
@Autowired
33+
BuildProperties build;
34+
2435
private ApiKey apiKey() {
2536
return new ApiKey("JWT", "Authorization", "header");
2637
}
2738

2839
private SecurityContext securityContext() {
29-
return SecurityContext.builder().securityReferences(defaultAuth()).build();
40+
return SecurityContext
41+
.builder()
42+
.securityReferences(defaultAuth()).build();
3043
}
3144

3245
private List<SecurityReference> defaultAuth() {
33-
AuthorizationScope authorizationScope = new AuthorizationScope(
34-
"global",
35-
"accessEverything"
36-
);
46+
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
3747
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
3848
authorizationScopes[0] = authorizationScope;
39-
return Arrays.asList(new SecurityReference("JWT", authorizationScopes));
49+
return asList(new SecurityReference("JWT", authorizationScopes));
4050
}
4151

4252
@Bean
4353
public Docket api() {
44-
return new Docket(DocumentationType.OAS_30)
54+
return new Docket(OAS_30)
4555
.useDefaultResponseMessages(false)
4656
.apiInfo(apiInfo())
47-
.securityContexts(Arrays.asList( securityContext()))
48-
.securitySchemes(Arrays.asList(apiKey()))
49-
.select()
50-
.apis(RequestHandlerSelectors.basePackage("com.github.throyer.common.springboot.api"))
51-
.paths(PathSelectors.any())
52-
.build();
57+
.securityContexts(asList(securityContext()))
58+
.securitySchemes(asList(apiKey())).select()
59+
.apis(basePackage("com.github.throyer.common.springboot.controllers.api"))
60+
.paths(any())
61+
.build()
62+
.useDefaultResponseMessages(false)
63+
.globalResponses(HttpMethod.GET, List.of(
64+
new ResponseBuilder().code("500").description("Internal Server Error").build(),
65+
new ResponseBuilder().code("403").description("Forbidden").build(),
66+
new ResponseBuilder().code("404").description("Not Found").build()
67+
)).globalResponses(HttpMethod.POST, List.of(
68+
new ResponseBuilder().code("500").description("Internal Server Error").build(),
69+
new ResponseBuilder().code("403").description("Forbidden").build(),
70+
new ResponseBuilder().code("404").description("Not Found").build(),
71+
new ResponseBuilder().code("400").description("Bad Request").build(),
72+
new ResponseBuilder().code("422").description("Unprocessable Entity").build(),
73+
new ResponseBuilder().code("409").description("Conflict").build()
74+
)).globalResponses(HttpMethod.PUT, List.of(
75+
new ResponseBuilder().code("500").description("Internal Server Error").build(),
76+
new ResponseBuilder().code("403").description("Forbidden").build(),
77+
new ResponseBuilder().code("400").description("Bad Request").build(),
78+
new ResponseBuilder().code("422").description("Unprocessable Entity").build(),
79+
new ResponseBuilder().code("409").description("Conflict").build(),
80+
new ResponseBuilder().code("404").description("Not Found").build()
81+
)).globalResponses(HttpMethod.DELETE, List.of(
82+
new ResponseBuilder().code("500").description("Internal Server Error").build(),
83+
new ResponseBuilder().code("404").description("Not Found").build()
84+
));
5385
}
5486

5587
private ApiInfo apiInfo() {
5688
return new ApiInfo(
57-
"Common API",
89+
build.getName(),
5890
"Exemplo de api simples com Spring Boot",
59-
"1.0.0",
91+
build.getVersion(),
6092
"https://github.com/Throyer",
61-
new Contact(
62-
"Throyer",
63-
"https://github.com/Throyer",
64-
"throyer.dev@gmail.com"
65-
),
93+
new Contact("Throyer", "https://github.com/Throyer", "throyer.dev@gmail.com"),
6694
"GNU General Public License v3.0",
6795
"https://github.com/Throyer/springboot-api-crud/blob/master/LICENSE",
68-
Collections.emptyList()
96+
emptyList()
6997
);
7098
}
7199
}

src/main/java/com/github/throyer/common/springboot/controllers/api/ApiController.java

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,15 @@
55
import org.springframework.web.bind.annotation.RestController;
66

77
import io.swagger.annotations.Api;
8+
import com.github.throyer.common.springboot.utils.Hello;
89

9-
@Api(tags = "Status check")
10+
@Api(tags = "Status check", produces = "application/json")
1011
@RestController
1112
@RequestMapping("/api")
1213
public class ApiController {
1314

14-
public class StatusCheck {
15-
private final String message = "Is a live!";
16-
public String getMessage() {
17-
return message;
18-
}
19-
}
20-
21-
private StatusCheck status = new StatusCheck();
22-
2315
@GetMapping
24-
public StatusCheck index() {
25-
return status;
16+
public Hello index() {
17+
return () -> "Is a live!";
2618
}
27-
}
19+
}

src/main/java/com/github/throyer/common/springboot/controllers/api/RecoveriesController.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
package com.github.throyer.common.springboot.controllers.api;
22

3+
import static org.springframework.http.HttpStatus.NO_CONTENT;
4+
35
import com.github.throyer.common.springboot.domain.services.user.RecoveryPasswordService;
46
import com.github.throyer.common.springboot.domain.services.user.dto.RecoveryConfirm;
57
import com.github.throyer.common.springboot.domain.services.user.dto.RecoveryRequest;
68
import com.github.throyer.common.springboot.domain.services.user.dto.RecoveryUpdate;
79

810
import org.springframework.beans.factory.annotation.Autowired;
9-
import org.springframework.http.HttpStatus;
1011
import org.springframework.web.bind.annotation.PostMapping;
1112
import org.springframework.web.bind.annotation.RequestBody;
1213
import org.springframework.web.bind.annotation.RequestMapping;
@@ -23,8 +24,8 @@ public class RecoveriesController {
2324
@Autowired
2425
private RecoveryPasswordService service;
2526

26-
@ResponseStatus(HttpStatus.NO_CONTENT)
2727
@PostMapping
28+
@ResponseStatus(NO_CONTENT)
2829
public void index(@RequestBody RecoveryRequest request) {
2930
service.recovery(request.getEmail());
3031
}
@@ -34,8 +35,8 @@ public void confirm(@RequestBody RecoveryConfirm confirm) {
3435
service.confirm(confirm.getEmail(), confirm.getCode());
3536
}
3637

37-
@ResponseStatus(HttpStatus.NO_CONTENT)
3838
@PostMapping("/update")
39+
@ResponseStatus(NO_CONTENT)
3940
public void update(@RequestBody RecoveryUpdate update) {
4041
service.update(update.getEmail(), update.getCode(), update.getPassword());
4142
}

src/main/java/com/github/throyer/common/springboot/controllers/api/UsersController.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.github.throyer.common.springboot.controllers.api;
22

3+
import static org.springframework.http.HttpStatus.CREATED;
4+
import static org.springframework.http.HttpStatus.NO_CONTENT;
5+
36
import com.github.throyer.common.springboot.domain.models.entity.User;
47
import com.github.throyer.common.springboot.domain.models.pagination.Page;
58
import com.github.throyer.common.springboot.domain.models.pagination.Pagination;
@@ -14,7 +17,6 @@
1417

1518
import org.springframework.beans.factory.annotation.Autowired;
1619
import org.springframework.data.domain.Sort;
17-
import org.springframework.http.HttpStatus;
1820
import org.springframework.http.ResponseEntity;
1921
import org.springframework.security.access.prepost.PreAuthorize;
2022
import org.springframework.validation.annotation.Validated;
@@ -59,8 +61,8 @@ public ResponseEntity<UserDetails> show(@PathVariable Long id) {
5961
return findService.find(id);
6062
}
6163

62-
@ResponseStatus(HttpStatus.CREATED)
6364
@PostMapping
65+
@ResponseStatus(CREATED)
6466
public ResponseEntity<UserDetails> save(@Validated @RequestBody CreateUser body) {
6567
return createService.create(body);
6668
}
@@ -74,9 +76,9 @@ public ResponseEntity<UserDetails> update(
7476
return updateService.update(id, body);
7577
}
7678

77-
@ResponseStatus(code = HttpStatus.NO_CONTENT)
78-
@PreAuthorize("hasAnyAuthority('ADM')")
7979
@DeleteMapping("/{id}")
80+
@ResponseStatus(NO_CONTENT)
81+
@PreAuthorize("hasAnyAuthority('ADM')")
8082
public ResponseEntity<User> destroy(@PathVariable Long id) {
8183
return removeService.remove(id);
8284
}

src/main/java/com/github/throyer/common/springboot/domain/builders/UserBuilder.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
public class UserBuilder {
1010

11-
private User user;
11+
private final User user;
1212
private List<Role> roles = new ArrayList<>();
1313

1414
public static UserBuilder createUser(String name) {
@@ -36,7 +36,7 @@ public UserBuilder setId(Long id) {
3636
return this;
3737
}
3838

39-
public UserBuilder setAtivo(Boolean active) {
39+
public UserBuilder setActive(Boolean active) {
4040
user.setActive(active);
4141
return this;
4242
}

src/main/java/com/github/throyer/common/springboot/domain/models/entity/Auditable.java

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
package com.github.throyer.common.springboot.domain.models.entity;
22

33
import static com.github.throyer.common.springboot.domain.services.security.SecurityService.authorized;
4+
import static java.time.LocalDateTime.now;
5+
import static java.util.Optional.ofNullable;
6+
import static javax.persistence.FetchType.LAZY;
47

58
import java.time.LocalDateTime;
69
import java.util.Optional;
710

811
import javax.persistence.Column;
9-
import javax.persistence.FetchType;
1012
import javax.persistence.JoinColumn;
1113
import javax.persistence.ManyToOne;
1214
import javax.persistence.MappedSuperclass;
@@ -21,15 +23,6 @@ public abstract class Auditable implements Entity {
2123

2224
public static final String NON_DELETED_CLAUSE = "deleted_at IS NULL";
2325

24-
public static final String SET_ALL_DELETED_SQL = """
25-
UPDATE
26-
#{#entityName}
27-
SET
28-
deleted_at = CURRENT_TIMESTAMP
29-
""";
30-
31-
public static final String SET_DELETED_SQL = SET_ALL_DELETED_SQL + "WHERE id = ?1";
32-
3326
@Override
3427
public abstract Long getId();
3528

@@ -46,30 +39,30 @@ public abstract class Auditable implements Entity {
4639
private LocalDateTime deletedAt;
4740

4841
@JoinColumn(name = "created_by")
49-
@ManyToOne(optional = true, fetch = FetchType.LAZY)
42+
@ManyToOne(optional = true, fetch = LAZY)
5043
private User createdBy;
5144

5245
@JoinColumn(name = "updated_by")
53-
@ManyToOne(optional = true, fetch = FetchType.LAZY)
46+
@ManyToOne(optional = true, fetch = LAZY)
5447
private User updatedBy;
5548

5649
@JoinColumn(name = "deleted_by")
57-
@ManyToOne(optional = true, fetch = FetchType.LAZY)
50+
@ManyToOne(optional = true, fetch = LAZY)
5851
private User deletedBy;
5952

6053
@JsonIgnore
6154
public Optional<User> getCreatedBy() {
62-
return Optional.ofNullable(createdBy);
55+
return ofNullable(createdBy);
6356
}
6457

6558
@JsonIgnore
6659
public Optional<User> getUpdatedBy() {
67-
return Optional.ofNullable(updatedBy);
60+
return ofNullable(updatedBy);
6861
}
6962

7063
@JsonIgnore
7164
public Optional<User> getDeletedBy() {
72-
return Optional.ofNullable(deletedBy);
65+
return ofNullable(deletedBy);
7366
}
7467

7568
@Column(name = "active", nullable = false)
@@ -109,15 +102,15 @@ public void setActive(Boolean active) {
109102

110103
@PrePersist
111104
private void save() {
112-
createdAt = LocalDateTime.now();
105+
createdAt = now();
113106
createdBy = authorized()
114107
.map(authorized -> new User(authorized.getId()))
115108
.orElse(null);
116109
}
117110

118111
@PreUpdate
119112
private void update() {
120-
updatedAt = LocalDateTime.now();
113+
updatedAt = now();
121114
updatedBy = authorized()
122115
.map(authorized -> new User(authorized.getId()))
123116
.orElse(null);

src/main/java/com/github/throyer/common/springboot/domain/models/entity/Role.java

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,24 +19,6 @@
1919
@Where(clause = Auditable.NON_DELETED_CLAUSE)
2020
public class Role extends Auditable implements GrantedAuthority {
2121

22-
public static final String DELETE_SQL = """
23-
UPDATE
24-
#{#entityName}
25-
SET
26-
deleted_name = (
27-
SELECT name FROM #{#entityName} WHERE id = ?1
28-
),
29-
name = NULL,
30-
deleted_initials = (
31-
SELECT name FROM #{#entityName} WHERE id = ?1
32-
),
33-
initials = NULL,
34-
deleted_at = CURRENT_TIMESTAMP,
35-
active = 0,
36-
deleted_by = ?#{principal?.id}
37-
WHERE id = ?1
38-
""";
39-
4022
private static final long serialVersionUID = -8524505911742593369L;
4123

4224
@Id

src/main/java/com/github/throyer/common/springboot/domain/models/entity/User.java

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,6 @@
3535
public class User extends Auditable implements Serializable, HasEmail {
3636

3737
public static final Integer PASSWORD_STRENGTH = 10;
38-
public static final String DELETE_SQL = """
39-
UPDATE
40-
#{#entityName}
41-
SET
42-
deleted_email = (
43-
SELECT
44-
email
45-
FROM
46-
#{#entityName}
47-
WHERE id = ?1),
48-
email = NULL,
49-
deleted_at = CURRENT_TIMESTAMP,
50-
active = 0,
51-
deleted_by = ?#{principal?.id}
52-
WHERE id = ?1
53-
""";
5438

5539
private static final long serialVersionUID = -8080540494839892473L;
5640

0 commit comments

Comments
 (0)