Skip to content

hrytsenko/json-data-spring-boot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status Quality Gate Status

Summary

This library enables json-data for Spring Boot including serialization, validation and error handling for HTTP requests and responses that use JSON entities.

Example

The following example illustrates:

@EnableFeignClients
@SpringBootApplication
class Application {

    static class Request extends JsonEntity<Request> {
        String getOwner() {
            return getString("owner");
        }
    }

    static class Response extends JsonEntity<Response> {
    }

    @RestController
    @AllArgsConstructor
    static class GithubController {

        static JsonMapper<Response> TO_RESPONSE = JsonMapper.create(
                JsonResources.readResource("/response-projection.json"), Response::new);

        GithubClient githubClient;

        @PostMapping(
                value = "/list-repositories",
                consumes = MediaType.APPLICATION_JSON_VALUE,
                produces = MediaType.APPLICATION_JSON_VALUE)
        @ValidateRequest("/request-schema.json")
        @ValidateResponse("/response-schema.json")
        @WrapErrors("CANNOT_LIST_REPOSITORIES")
        public Response listRepositories(@RequestBody Request request) {
            val repositories = githubClient.listRepositories(request.getOwner());
            return TO_RESPONSE.map(repositories);
        }

        @FeignClient(
                name = "github-client",
                url = "${github.url}")
        interface GithubClient {
            @GetMapping(
                    value = "/users/{owner}/repos",
                    produces = MediaType.APPLICATION_JSON_VALUE)
            List<JsonBean> listRepositories(@PathVariable("owner") String owner);
        }

    }

    @Bean
    public CorrelationSource sleuthSource(Tracer tracer) {
        return () -> tracer.currentSpan().context().traceIdString();
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

Usage

Use JSON entities with Spring Web and Spring Feign.

Use ValidateRequest to validate a JSON entity (the first argument) via JSON Schema. Use ValidateResponse to validate a JSON entity (the return value) via JSON Schema.

Use WrapErrors to wrap all exceptions in ServiceException.InternalError with a given error code, except those that are ServiceException.

Provide CorrelationSource to enable correlations for error responses.

Provide ValidatorSource to configure a resource manager for validators.

About

JSON Data for Spring Boot 2.

Topics

Resources

License

Stars

Watchers

Forks

Contributors 2

  •  
  •  

Languages