001/* 002 * Copyright 2016 Anyware Services 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 */ 016package org.ametys.plugins.core.impl.validator; 017 018import java.util.regex.Pattern; 019import java.util.regex.PatternSyntaxException; 020 021import org.apache.avalon.framework.configuration.Configuration; 022import org.apache.avalon.framework.configuration.ConfigurationException; 023 024import org.ametys.runtime.i18n.I18nizableText; 025import org.ametys.runtime.parameter.DefaultValidator; 026import org.ametys.runtime.parameter.Errors; 027 028/** 029 * This validator validates that the regular expression set is valid 030 * 031 */ 032public class RegexpValidator extends DefaultValidator 033{ 034 @Override 035 public void configure(Configuration configuration) throws ConfigurationException 036 { 037 Configuration validatorConfig = configuration.getChild("validation").getChild("custom-validator"); 038 039 _isMandatory = validatorConfig.getChild("mandatory", false) != null; 040 041 String regexp = validatorConfig.getChild("regexp").getValue(null); 042 if (regexp != null) 043 { 044 _regexp = Pattern.compile(regexp); 045 } 046 047 Configuration textConfig = validatorConfig.getChild("invalidText", false); 048 if (textConfig != null) 049 { 050 _invalidText = I18nizableText.parseI18nizableText(textConfig, "plugin." + _pluginName); 051 } 052 } 053 054 @Override 055 protected void validateSingleValue(Object value, Errors errors) 056 { 057 super.validateSingleValue(value, errors); 058 059 _validateRegexp((String) value, errors); 060 } 061 062 @Override 063 protected void validateArrayValues(Object[] values, Errors errors) 064 { 065 super.validateArrayValues(values, errors); 066 067 for (Object value : values) 068 { 069 _validateRegexp((String) value, errors); 070 } 071 } 072 073 private void _validateRegexp (String regexp, Errors errors) 074 { 075 if (regexp != null) 076 { 077 try 078 { 079 Pattern.compile(regexp); 080 } 081 catch (PatternSyntaxException e) 082 { 083 if (getLogger().isDebugEnabled()) 084 { 085 getLogger().debug("The regular expression '" + regexp + "' is not a valid one."); 086 } 087 088 errors.addError(new I18nizableText("plugin.core-impl", "PLUGINS_CORE_VALIDATOR_REGEXP_FAILED")); 089 } 090 } 091 } 092}