|
| 1 | +/* |
| 2 | + * Copyright (c) 2016 Network New Technologies Inc. |
| 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 | + |
| 17 | +package com.networknt.schema; |
| 18 | + |
| 19 | +import com.fasterxml.jackson.databind.JsonNode; |
| 20 | +import org.slf4j.Logger; |
| 21 | +import org.slf4j.LoggerFactory; |
| 22 | + |
| 23 | +import java.text.ParsePosition; |
| 24 | +import java.text.SimpleDateFormat; |
| 25 | +import java.util.Collections; |
| 26 | +import java.util.LinkedHashSet; |
| 27 | +import java.util.Set; |
| 28 | +import java.util.regex.Matcher; |
| 29 | +import java.util.regex.Pattern; |
| 30 | + |
| 31 | +public class UUIDValidator extends BaseJsonValidator implements JsonValidator { |
| 32 | + private static final Logger logger = LoggerFactory.getLogger(UUIDValidator.class); |
| 33 | + |
| 34 | + private final String formatName; |
| 35 | + |
| 36 | + |
| 37 | + private static final String regex = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"; |
| 38 | + |
| 39 | + public UUIDValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext, String formatName) { |
| 40 | + super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.DATETIME, validationContext); |
| 41 | + this.formatName = formatName; |
| 42 | + parseErrorCode(getValidatorType().getErrorCodeKey()); |
| 43 | + } |
| 44 | + |
| 45 | + public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) { |
| 46 | + debug(logger, node, rootNode, at); |
| 47 | + |
| 48 | + Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>(); |
| 49 | + |
| 50 | + JsonType nodeType = TypeFactory.getValueNodeType(node); |
| 51 | + if (nodeType != JsonType.STRING) { |
| 52 | + return errors; |
| 53 | + } |
| 54 | + if (!isUUID(node.textValue())) { |
| 55 | + errors.add(buildValidationMessage(at, node.textValue(), formatName)); |
| 56 | + } |
| 57 | + return Collections.unmodifiableSet(errors); |
| 58 | + } |
| 59 | + |
| 60 | + public boolean isUUID(String s){ |
| 61 | + return s.matches(regex); |
| 62 | + } |
| 63 | +} |
0 commit comments