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.util.Iterables;
19 import org.modelmapper.internal.util.MappingContextHelper;
20 import org.modelmapper.spi.ConditionalConverter;
21 import org.modelmapper.spi.MappingContext;
22
23 import java.util.Collection;
24 import java.util.Iterator;
25
26 /**
27  * Converts {@link Collection} and array instances to {@link Collection} instances.
28  *
29  * @author Jonathan Halterman
30  */

31 public class MergingCollectionConverter implements ConditionalConverter<Object, Collection<Object>> {
32   @Override
33   public MatchResult match(Class<?> sourceType, Class<?> destinationType) {
34     return Iterables.isIterable(sourceType) && Collection.class.isAssignableFrom(destinationType) ? MatchResult.FULL
35         : MatchResult.NONE;
36   }
37
38   @Override
39   public Collection<Object> convert(MappingContext<Object, Collection<Object>> context) {
40     Object source = context.getSource();
41     if (source == null)
42       return null;
43
44     int sourceLength = Iterables.getLength(source);
45     Collection<Object> originalDestination = context.getDestination();
46     Collection<Object> destination = MappingContextHelper.createCollection(context);
47     Class<?> elementType = MappingContextHelper.resolveDestinationGenericType(context);
48
49     int index = 0;
50     for (Iterator<Object> iterator = Iterables.iterator(source); iterator.hasNext(); index++) {
51       Object sourceElement = iterator.next();
52       Object element = null;
53       if (originalDestination != null)
54         element = Iterables.getElement(originalDestination, index);
55       if (sourceElement != null) {
56         MappingContext<?, ?> elementContext = element == null
57             ? context.create(sourceElement, elementType)
58             : context.create(sourceElement, element);
59         element = context.getMappingEngine().map(elementContext);
60       }
61       destination.add(element);
62     }
63     for (Object element : Iterables.subIterable(originalDestination, sourceLength))
64       destination.add(element);
65
66     return destination;
67   }
68 }
69