1
16 package org.modelmapper.internal.converter;
17
18 import org.modelmapper.internal.Errors;
19 import org.modelmapper.spi.ConditionalConverter;
20 import org.modelmapper.spi.MappingContext;
21
22
27 class BooleanConverter implements ConditionalConverter<Object, Boolean> {
28 private static final String[] TRUE_STRINGS = { "true", "yes", "y", "on", "1" };
29 private static final String[] FALSE_STRINGSS = { "false", "no", "n", "off", "0" };
30
31 public Boolean convert(MappingContext<Object, Boolean> context) {
32 Object source = context.getSource();
33 if (source == null)
34 return null;
35
36 String stringValue = source.toString().toLowerCase();
37 if (stringValue.length() == 0)
38 return null;
39
40 for (int i = 0; i < TRUE_STRINGS.length; i++)
41 if (TRUE_STRINGS[i].equals(stringValue))
42 return Boolean.TRUE;
43
44 for (int i = 0; i < FALSE_STRINGSS.length; i++)
45 if (FALSE_STRINGSS[i].equals(stringValue))
46 return Boolean.FALSE;
47
48 throw new Errors().errorMapping(context.getSource(), context.getDestinationType())
49 .toMappingException();
50 }
51
52 public MatchResult match(Class<?> sourceType, Class<?> destinationType) {
53 boolean destMatch = destinationType == Boolean.class || destinationType == Boolean.TYPE;
54 return destMatch ? sourceType == Boolean.class || sourceType == Boolean.TYPE ? MatchResult.FULL
55 : MatchResult.PARTIAL : MatchResult.NONE;
56 }
57 }