Skip to content

Commit

Permalink
Initial commit...
Browse files Browse the repository at this point in the history
  • Loading branch information
JanLoebel committed Dec 21, 2019
0 parents commit 1da3eed
Show file tree
Hide file tree
Showing 13 changed files with 405 additions and 0 deletions.
1 change: 1 addition & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
custom: https://paypal.me/janloebel
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Maven
target

# Eclipse
.settings/
.classpath
.project
.factorypath

# IntelliJ
*.iml
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Jan Löbel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Json-Schema-Validation-Starter

This provides a Spring-Boot-Starter to include JsonSchemaValidation with the help of the [https://github.com/networknt/json-schema-validator](https://github.com/networknt/json-schema-validator) -library.

## Usage

Include the starter into you're project.

You need to add jitpack to your `pom.xml` because this project is not available in the official maven repository.
```
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
```

Add the `json-schema-validation-starter`-dependency to your `pom.xml`
```
<dependency>
<groupId>com.github.JanLoebel</groupId>
<artifactId>json-schema-validation-starter</artifactId>
<version>1.0.0</version>
</dependency>
```

After that simply create a json-schema and put it into e.g.: `resources/jsonschema/book.json`.
The last step is now to let your entity know that it should be validated and which schema it should use.

```
@JsonSchemaValidation("classpath:jsonschema/book.json")
public class Book {
private String title;
private String author;
}
```

## Example project
Head over to [http://github.com/JanLoebel/json-schema-validation-starter-example](http://github.com/JanLoebel/json-schema-validation-starter-example) to checkout the sample project.

## Contribution
Please feel free to improve or modify the code and open a Pull-Request! Any contribution is welcome :)

## License
MIT License

Copyright (c) 2019 Jan Löbel

See LICENSE file for details.
52 changes: 52 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.github.JanLoebel</groupId>
<artifactId>json-schema-validation-starter</artifactId>
<version>1.0.0-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>2.2.2.RELEASE</spring-boot.version>
<spring.version>5.2.2.RELEASE</spring.version>
<java.version>8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>1.0.29</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.github.JanLoebel.jsonschemavalidation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonSchemaValidation {

String value();

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.github.JanLoebel.jsonschemavalidation;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.JanLoebel.jsonschemavalidation.advice.JsonValidationRequestBodyControllerAdvice;
import com.github.JanLoebel.jsonschemavalidation.provider.DefaultJsonSchemaProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JsonSchemaValidationAutoConfiguration {

@Bean
@ConditionalOnMissingBean
public JsonValidationRequestBodyControllerAdvice jsonValidationRequestBodyControllerAdvice(ObjectMapper objectMapper) {
return new JsonValidationRequestBodyControllerAdvice(objectMapper, new DefaultJsonSchemaProvider());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.github.JanLoebel.jsonschemavalidation;

import com.networknt.schema.ValidationMessage;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;

import java.util.Collection;
import java.util.stream.Collectors;

public class JsonSchemaValidationException extends ResponseStatusException {

private final Collection<ValidationMessage> validationMessages;

public JsonSchemaValidationException(Collection<ValidationMessage> validationMessages) {
super(HttpStatus.BAD_REQUEST, buildMessage(validationMessages));
this.validationMessages = validationMessages;
}

private static String buildMessage(Collection<ValidationMessage> validationMessages) {
final String prefix = "JsonSchemaValidation failed: ";
return prefix + validationMessages
.stream()
.map(ValidationMessage::toString)
.collect(Collectors.joining(", "));
}

public Collection<ValidationMessage> getValidationMessages() {
return this.validationMessages;
}

@Override
public String toString() {
return "JsonSchemaValidationException{" +
"validationMessages=" + validationMessages +
'}';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.github.JanLoebel.jsonschemavalidation.advice;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.JanLoebel.jsonschemavalidation.JsonSchemaValidation;
import com.github.JanLoebel.jsonschemavalidation.provider.JsonSchemaProvider;
import com.networknt.schema.ValidationMessage;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.Set;

@ControllerAdvice
public class JsonValidationRequestBodyControllerAdvice implements RequestBodyAdvice {

private ObjectMapper objectMapper;
private JsonSchemaProvider jsonSchemaProvider;

public JsonValidationRequestBodyControllerAdvice(ObjectMapper objectMapper, JsonSchemaProvider jsonSchemaProvider) {
this.objectMapper = objectMapper;
this.jsonSchemaProvider = jsonSchemaProvider;
}

@Override
public boolean supports(MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
return parameter.getNestedParameterType().isAnnotationPresent(JsonSchemaValidation.class);
}

@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType)
throws IOException {
final String body = toString(inputMessage);

final String uri = extractSchemaUri(parameter);
final JsonNode jsonNode = this.objectMapper.readTree(body);
final Set<ValidationMessage> validationMessages = this.jsonSchemaProvider.loadSchema(uri).validate(jsonNode);
this.jsonSchemaProvider.handleValidationMessages(validationMessages);

return buildHttpInputMessage(body, inputMessage.getHeaders());
}

private String extractSchemaUri(MethodParameter parameter) {
final JsonSchemaValidation annotation =
parameter.getNestedParameterType().getAnnotation(JsonSchemaValidation.class);
return annotation.value();
}

@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
// Do not touch
return body;
}

@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
// Do not touch
return body;
}

private String toString(HttpInputMessage inputMessage) throws IOException {
final InputStream inputStream = inputMessage.getBody();
return StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
}

private InputStream fromString(String body) {
return new ByteArrayInputStream(body.getBytes());
}

private HttpInputMessage buildHttpInputMessage(String body, HttpHeaders httpHeaders) {
return new HttpInputMessage() {
@Override
public InputStream getBody() {
return fromString(body);
}

@Override
public HttpHeaders getHeaders() {
return httpHeaders;
}
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.github.JanLoebel.jsonschemavalidation.provider;

import com.networknt.schema.JsonSchema;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CacheableJsonSchemaProvider extends DefaultJsonSchemaProvider {

private final Map<String, JsonSchema> cache = new ConcurrentHashMap<>();
private final String basePath;

public CacheableJsonSchemaProvider(String basePath) {
this.basePath = basePath;
}

public CacheableJsonSchemaProvider() {
this("");
}

@Override
public JsonSchema loadSchema(String url) {
final String fullPath = basePath + url;
if (cache.containsKey(fullPath)) {
return cache.get(fullPath);
}

return putToCache(fullPath, super.loadSchema(fullPath));
}

private JsonSchema putToCache(String fullPath, JsonSchema jsonSchema) {
cache.put(fullPath, jsonSchema);
return jsonSchema;
}

}
Loading

0 comments on commit 1da3eed

Please sign in to comment.