001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.api.util.validators.identifierschemes;
015
016import java.util.Objects;
017import java.util.regex.Matcher;
018import java.util.regex.Pattern;
019
020/**
021 *  Validator for Orcid identifiers.
022 */
023public class OrcidValidator implements IdentifierSchemeValidator {
024
025  private static final Pattern ORCID_PATTERN = Pattern.compile("^(?<scheme>http(?:s)?:\\/\\/orcid.org\\/)?(([0-9]{4}-){3}([0-9]{3}[0-9X]{1}))$");
026
027  @Override
028  public boolean isValid(String value) {
029    if (value == null || value.isEmpty()) {
030      return false;
031    }
032    Matcher matcher = ORCID_PATTERN.matcher(value);
033    return matcher.matches() && Mod112.hasValidChecksumDigit(withoutScheme(matcher, value));
034  }
035
036  @Override
037  public String normalize(String value) {
038    Objects.requireNonNull(value, "Identifier value can't be null");
039    String trimmedValue = value.trim();
040    Matcher matcher = ORCID_PATTERN.matcher(trimmedValue);
041    if (matcher.matches()) {
042      return IdentifierScheme.ORCID.getSchemeURI() + '/' + withoutScheme(matcher, trimmedValue);
043    }
044    throw new IllegalArgumentException(value + " it not a valid Orcid");
045  }
046
047  /**
048   * This
049   */
050  private static String withoutScheme(Matcher matcher, String value) {
051    String schemeGroup = matcher.group("scheme");
052    return schemeGroup == null ? value : value.substring(schemeGroup.length());
053  }
054
055}