    001// Copyright 2007 The Apache Software Foundation
    002//
    003// Licensed under the Apache License, Version 2.0 (the "License");
    004// you may not use this file except in compliance with the License.
    005// You may obtain a copy of the License at
    006//
    007//     http://www.apache.org/licenses/LICENSE-2.0
    008//
    009// Unless required by applicable law or agreed to in writing, software
    010// distributed under the License is distributed on an "AS IS" BASIS,
    011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    012// See the License for the specific language governing permissions and
    013// limitations under the License.
    014
    015package org.apache.tapestry5.internal.beaneditor;
    016
    017import org.apache.tapestry5.services.ValidationConstraintGenerator;
    018import org.apache.tapestry5.services.Environment;
    019import org.apache.tapestry5.services.PropertyEditContext;
    020import org.apache.tapestry5.ioc.AnnotationProvider;
    021import org.apache.tapestry5.ioc.Messages;
    022import org.apache.tapestry5.ioc.internal.util.InternalUtils;
    023
    024import java.util.List;
    025import java.util.Arrays;
    026import java.util.regex.Pattern;
    027
    028/**
    029 * Generates constraints from the containing component's property file.
    030 * Looks for a key in the form: propertyId-validate.
    031 *
    032 */
    033public class MessagesConstraintGenerator implements ValidationConstraintGenerator
    034{
    035
    036    private final Environment environment;
    037    private final Pattern splitPattern;
    038
    039    public MessagesConstraintGenerator(final Environment environment) {
    040        this.environment = environment;
    041        splitPattern = Pattern.compile(ValidateAnnotationConstraintGenerator.VALIDATOR_PATTERN);
    042    }
    043
    044    public List<String> buildConstraints(Class propertyType, AnnotationProvider annotationProvider)
    045    {
    046        EnvironmentMessages environmentMessages = environment.peek(EnvironmentMessages.class);
    047        if (environmentMessages == null) {
    048            return null;
    049        }
    050
    051        String key = environmentMessages.getOverrideId() + "-validate";
    052        Messages m = environmentMessages.getMessages();
    053        if (!m.contains(key))
    054        {
    055            return null;
    056        }
    057
    058        String result = m.get(key);
    059        if (InternalUtils.isBlank(result))
    060        {
    061            return null;
    062        }
    063        return Arrays.asList(splitPattern.split(result));
    064    }
    065}