001/* 002 * Copyright 2012-2017 the original author or authors. 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 017package org.springframework.boot.validation; 018 019import java.util.Collections; 020import java.util.LinkedHashSet; 021import java.util.Set; 022 023import javax.validation.MessageInterpolator; 024import javax.validation.Validation; 025import javax.validation.ValidationException; 026 027import org.springframework.beans.BeanUtils; 028import org.springframework.beans.BeansException; 029import org.springframework.beans.factory.ObjectFactory; 030import org.springframework.util.ClassUtils; 031 032/** 033 * {@link ObjectFactory} that can be used to create a {@link MessageInterpolator}. 034 * Attempts to pick the most appropriate {@link MessageInterpolator} based on the 035 * classpath. 036 * 037 * @author Phillip Webb 038 */ 039public class MessageInterpolatorFactory implements ObjectFactory<MessageInterpolator> { 040 041 private static final Set<String> FALLBACKS; 042 043 static { 044 Set<String> fallbacks = new LinkedHashSet<>(); 045 fallbacks.add("org.hibernate.validator.messageinterpolation" 046 + ".ParameterMessageInterpolator"); 047 FALLBACKS = Collections.unmodifiableSet(fallbacks); 048 } 049 050 @Override 051 public MessageInterpolator getObject() throws BeansException { 052 try { 053 return Validation.byDefaultProvider().configure() 054 .getDefaultMessageInterpolator(); 055 } 056 catch (ValidationException ex) { 057 MessageInterpolator fallback = getFallback(); 058 if (fallback != null) { 059 return fallback; 060 } 061 throw ex; 062 } 063 } 064 065 private MessageInterpolator getFallback() { 066 for (String fallback : FALLBACKS) { 067 try { 068 return getFallback(fallback); 069 } 070 catch (Exception ex) { 071 // Swallow an continue 072 } 073 } 074 return null; 075 } 076 077 private MessageInterpolator getFallback(String fallback) { 078 Class<?> interpolatorClass = ClassUtils.resolveClassName(fallback, null); 079 Object interpolator = BeanUtils.instantiateClass(interpolatorClass); 080 return (MessageInterpolator) interpolator; 081 } 082 083}