|
| 1 | +/* |
| 2 | + * Copyright 2020-Present The Serverless Workflow Specification Authors |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.serverlessworkflow.serialization; |
| 17 | + |
| 18 | +import com.fasterxml.jackson.core.JsonParser; |
| 19 | +import com.fasterxml.jackson.databind.DeserializationContext; |
| 20 | +import com.fasterxml.jackson.databind.deser.BeanDeserializer; |
| 21 | +import com.fasterxml.jackson.databind.deser.BeanDeserializerBase; |
| 22 | +import jakarta.validation.ConstraintViolation; |
| 23 | +import jakarta.validation.ConstraintViolationException; |
| 24 | +import jakarta.validation.Validation; |
| 25 | +import jakarta.validation.Validator; |
| 26 | +import java.io.IOException; |
| 27 | +import java.util.Set; |
| 28 | + |
| 29 | +public class BeanDeserializerWithValidation extends BeanDeserializer { |
| 30 | + private static final long serialVersionUID = 1L; |
| 31 | + private static final Validator validator = |
| 32 | + Validation.buildDefaultValidatorFactory().getValidator(); |
| 33 | + |
| 34 | + protected BeanDeserializerWithValidation(BeanDeserializerBase src) { |
| 35 | + super(src); |
| 36 | + } |
| 37 | + |
| 38 | + private <T> void validate(T t) throws IOException { |
| 39 | + Set<ConstraintViolation<T>> violations = validator.validate(t); |
| 40 | + if (!violations.isEmpty()) { |
| 41 | + throw new ConstraintViolationException(violations); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { |
| 47 | + Object instance = super.deserialize(p, ctxt); |
| 48 | + validate(instance); |
| 49 | + return instance; |
| 50 | + } |
| 51 | +} |
0 commit comments