/**
*
* Copyright
* 2009-2015 Jayway Products AB
* 2016-2017 Föreningen Sambruk
*
* Licensed under AGPL, Version 3.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/agpl.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package se.streamsource.dci.restlet.server;
import org.qi4j.api.constraint.ConstraintViolation;
import java.lang.annotation.Annotation;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* TODO
*/
public class ConstraintViolationMessages
{
public String getMessage(ConstraintViolation violation, Locale locale)
throws IllegalArgumentException
{
try
{
ResourceBundle bundle = ResourceBundle.getBundle("ValidationMessages", locale);
Annotation annotation = violation.constraint();
String message;
try
{
message = (String) annotation.annotationType().getMethod("message").invoke(annotation);
} catch (Exception e1)
{
message = "{"+annotation.annotationType().getName()+".message"+"}";
}
while (message.startsWith("{"))
message = bundle.getString(message.substring(1, message.length()-1));
Pattern pattern = Pattern.compile("\\{[^\\}]*\\}");
String result = "";
Matcher matcher = pattern.matcher(message);
int start = 0;
while (matcher.find())
{
String match = matcher.group();
match = match.substring(1, match.length()-1);
result += message.substring(start, matcher.start());
if (match.equals("val"))
{
result += violation.value() == null ? "null" : violation.value().toString();
} else
{
result += annotation.annotationType().getMethod(match).invoke(annotation).toString();
}
start = matcher.end();
}
result += message.substring(start);
return result;
} catch (Exception e)
{
throw new IllegalArgumentException("Could not deduce message", e);
}
}
}