Add CasserValidator for property values

This commit is contained in:
Albert Shift 2015-06-09 14:55:57 -07:00
parent 49cb219849
commit c0b16c2db6
2 changed files with 109 additions and 0 deletions

View file

@ -0,0 +1,55 @@
/*
* Copyright (C) 2015 Noorq, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.noorq.casser.core;
import java.lang.annotation.Annotation;
import javax.validation.ConstraintValidator;
import com.noorq.casser.mapping.CasserProperty;
import com.noorq.casser.support.CasserException;
import com.noorq.casser.support.CasserMappingException;
public final class CasserValidator {
private CasserValidator() {
}
public static void validate(CasserProperty prop, Object value) {
for (ConstraintValidator<? extends Annotation, ?> validator : prop.getValidators()) {
ConstraintValidator typeless = (ConstraintValidator) validator;
boolean valid = false;
try {
valid = typeless.isValid(value, null);
}
catch(ClassCastException e) {
throw new CasserMappingException("validator was used for wrong type '" + value + "' in " + prop, e);
}
if (!valid) {
throw new CasserException("wrong value type '" + value + "' for " + prop);
}
}
}
}

View file

@ -0,0 +1,54 @@
package com.noorq.casser.test.integration.core;
import org.junit.Before;
import org.junit.Test;
import com.noorq.casser.core.Casser;
import com.noorq.casser.core.CasserValidator;
import com.noorq.casser.mapping.CasserEntity;
import com.noorq.casser.mapping.CasserProperty;
import com.noorq.casser.mapping.annotation.Constraints;
import com.noorq.casser.mapping.annotation.PartitionKey;
import com.noorq.casser.mapping.annotation.Table;
import com.noorq.casser.support.CasserException;
import com.noorq.casser.support.CasserMappingException;
public class CasserValidatorTest {
@Table
interface ModelForValidation {
@Constraints.Email
@PartitionKey
String id();
}
CasserEntity entity;
CasserProperty prop;
@Before
public void begin() {
entity = Casser.entity(ModelForValidation.class);
prop = entity.getProperty("id");
}
@Test(expected=CasserMappingException.class)
public void testWrongType() {
CasserValidator.validate(prop, Integer.valueOf(123));
}
@Test(expected=CasserException.class)
public void testWrongValue() {
CasserValidator.validate(prop, "123");
}
public void testOk() {
CasserValidator.validate(prop, "a@b.c");
}
}