001/*
002 * (C) Copyright 2014-2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nicolas Chapurlat <nchapurlat@nuxeo.com>
018 */
019
020package org.nuxeo.ecm.core.schema.types.constraints;
021
022import java.io.Serializable;
023import java.util.ArrayList;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Locale;
027import java.util.Map;
028import java.util.regex.Pattern;
029
030import org.apache.commons.lang3.StringUtils;
031
032/**
033 * This constraint ensures some object's String representation match a pattern.
034 *
035 * @since 7.1
036 */
037public class PatternConstraint extends AbstractConstraint {
038
039    private static final long serialVersionUID = 1L;
040
041    private static final String NAME = "PatternConstraint";
042
043    private static final String PNAME_PATTERN = "Pattern";
044
045    protected final Pattern pattern;
046
047    public PatternConstraint(String pattern) {
048        this.pattern = Pattern.compile(pattern);
049    }
050
051    @Override
052    public boolean validate(Object object) {
053        if (object == null) {
054            return true;
055        }
056        return pattern.matcher(object.toString()).matches();
057    }
058
059    /**
060     * Here, value is : <br>
061     * name = {@value #NAME} <br>
062     * parameters =
063     * <ul>
064     * <li>{@value #PNAME_PATTERN} : [0-9]+</li>
065     * </ul>
066     */
067    @Override
068    public Description getDescription() {
069        Map<String, Serializable> params = new HashMap<>();
070        params.put(PNAME_PATTERN, pattern.pattern());
071        return new Description(PatternConstraint.NAME, params);
072    }
073
074    /**
075     * @return The pattern used by this constraint to validate.
076     * @since 7.1
077     */
078    public String getPattern() {
079        return pattern.pattern();
080    }
081
082    @Override
083    public String getErrorMessage(Object invalidValue, Locale locale) {
084        // test whether there's a custom translation for this field constraint specific translation
085        // the expected key is label.schema.constraint.violation.[ConstraintName]
086        // follow the AbstractConstraint behavior otherwise
087        List<String> pathTokens = new ArrayList<>();
088        pathTokens.add(MESSAGES_KEY);
089        pathTokens.add(PatternConstraint.NAME);
090        String key = StringUtils.join(pathTokens, '.');
091        Object[] params = new Object[] { getPattern() };
092        Locale computedLocale = locale != null ? locale : Constraint.MESSAGES_DEFAULT_LANG;
093        String message = getMessageString(MESSAGES_BUNDLE, key, params, computedLocale);
094        if (message != null && !message.trim().isEmpty() && !key.equals(message)) {
095            // use a custom constraint message if there's one
096            return message;
097        } else {
098            // follow AbstractConstraint behavior otherwise
099            return super.getErrorMessage(invalidValue, computedLocale);
100        }
101    }
102
103    @Override
104    public int hashCode() {
105        final int prime = 31;
106        int result = 1;
107        result = prime * result + ((pattern == null) ? 0 : pattern.pattern().hashCode());
108        return result;
109    }
110
111    @Override
112    public boolean equals(Object obj) {
113        if (this == obj) {
114            return true;
115        }
116        if (obj == null) {
117            return false;
118        }
119        if (getClass() != obj.getClass()) {
120            return false;
121        }
122        PatternConstraint other = (PatternConstraint) obj;
123        if (pattern == null) {
124            if (other.pattern != null) {
125                return false;
126            }
127        } else if (!pattern.pattern().equals(other.pattern.pattern())) {
128            return false;
129        }
130        return true;
131    }
132
133}