1 /*
2  * Copyright 2011 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

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 /**
23  * Converts to {@link Boolean} instances.
24  * 
25  * @author Jonathan Halterman
26  */

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 }