View Javadoc
1   /*
2    * Copyright 2009 the original author or 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 org.openehealth.ipf.commons.ihe.xds.core.validate;
17  
18  import static org.apache.commons.lang3.Validate.notNull;
19  import static org.openehealth.ipf.commons.ihe.xds.core.validate.ValidationMessage.*;
20  import static org.openehealth.ipf.commons.ihe.xds.core.validate.ValidatorAssertions.metaDataAssert;
21  
22  import java.util.regex.Pattern;
23  
24  /**
25   * Validates time values.
26   * @author Jens Riemschneider
27   */
28  public class TimeValidator implements ValueValidator {
29      private static final String YEAR = "[0-9]{4}";
30      private static final String MONTH = "(0[1-9]|1[012])";
31      private static final String DAY = "(0[1-9]|[12][0-9]|3[01])";
32      private static final String HOUR = "([01][0-9]|2[0123])";
33      private static final String MIN_SEC = "[0-5][0-9]";
34      private static final String REG_EX =
35          YEAR + "(" + MONTH + "(" + DAY + "(" + HOUR + "(" + MIN_SEC + "(" + MIN_SEC + ")?)?)?)?)?";
36  
37      private static final Pattern TIME_PATTERN = Pattern.compile(REG_EX);
38  
39      private final int minLen;
40  
41      /**
42       * Initializes a validator which will check that the timestamp has the right format
43       * and the given minimal length (to check the precision).
44       *
45       * @param minLen minimal length of the timestamp; "-1" means no check.
46       */
47      public TimeValidator(int minLen) {
48          this.minLen = minLen;
49      }
50  
51      /**
52       * Initializes a validator which will check that the timestamp has the right format
53       * without minimal length constraint.
54       */
55      public TimeValidator() {
56          this(-1);
57      }
58  
59      @Override
60      public void validate(String time) throws XDSMetaDataException {
61          notNull(time, "time cannot be null");
62          metaDataAssert(TIME_PATTERN.matcher(time).matches(), INVALID_TIME, time);
63          metaDataAssert((minLen < 0) || (time.length() >= minLen), TIME_PRECISION_TOO_LOW, time);
64      }
65  }