001/* 002 * Copyright 2020 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.cms.contenttype.validation; 017 018import java.util.Optional; 019import java.util.stream.Stream; 020 021import org.ametys.cms.data.Reference; 022import org.ametys.runtime.i18n.I18nizableText; 023import org.ametys.runtime.parameter.DefaultValidator; 024import org.ametys.runtime.parameter.Errors; 025 026/** 027 * This is an implementation of {@link DefaultValidator} for {@link Reference}. 028 */ 029public class ReferenceValidator extends DefaultValidator 030{ 031 /** 032 * Default constructor for avalon 033 */ 034 public ReferenceValidator() 035 { 036 super(); 037 } 038 039 /** 040 * Manual constructor 041 * @param regexp The regexp to check or null 042 * @param mandatory Is the value mandatory 043 */ 044 public ReferenceValidator(String regexp, boolean mandatory) 045 { 046 super(regexp, mandatory); 047 } 048 049 /** 050 * Manual constructor 051 * @param regexp The regexp to check or null 052 * @param invalidText The error text to display 053 * @param mandatory Is the value mandatory 054 */ 055 public ReferenceValidator(String regexp, I18nizableText invalidText, boolean mandatory) 056 { 057 super(regexp, invalidText, mandatory); 058 } 059 060 @Override 061 public void validate(Object value, Errors errors) 062 { 063 boolean isArray = value != null && value.getClass().isArray(); 064 if (isArray) 065 { 066 assert value instanceof Reference[]; 067 Object[] internalValues = Stream.of((Reference[]) value) 068 .map(Reference::getValue) 069 .toArray(); 070 validateArrayValues(internalValues, errors); 071 } 072 else 073 { 074 assert value instanceof Reference; 075 String internalValue = Optional.ofNullable(value) 076 .map(Reference.class::cast) 077 .map(Reference::getValue) 078 .orElse(null); 079 validateSingleValue(internalValue, errors); 080 } 081 } 082}