com.tomtom.speedtools.mongodb.mappers.CollectionMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mongodb Show documentation
Show all versions of mongodb Show documentation
Generic utility classes for project SpeedTools.
/*
* Copyright (C) 2012-2017. TomTom International BV (http://tomtom.com).
*
* Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
*
* 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 com.tomtom.speedtools.mongodb.mappers;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class CollectionMapper extends Mapper> {
@Nullable
private Class> elementMapperType;
@Nullable
private Mapper elementMapper;
@Nonnull
public static CollectionMapper create(@Nonnull final Class> elementMapperType) {
assert elementMapperType != null;
return new CollectionMapper<>(elementMapperType, null);
}
@Nonnull
public static CollectionMapper create(@Nonnull final Mapper elementMapper) {
assert elementMapper != null;
return new CollectionMapper<>(null, elementMapper);
}
protected CollectionMapper(@Nullable final Class> elementMapperType,
@Nullable final Mapper elementMapper) {
super();
this.elementMapperType = elementMapperType;
this.elementMapper = elementMapper;
}
@Nonnull
public Mapper getElementMapper() {
assert elementMapper != null;
return elementMapper;
}
@Override
public Collection fromDb(@Nullable final Object dbValue) throws MapperException {
// Only one object? Map it to a singleton-set.
final Collection collection;
if (dbValue == null) {
collection = Collections.emptyList();
} else if (dbValue instanceof Collection) {
collection = (Collection) dbValue;
} else {
collection = Collections.singletonList(dbValue);
}
// Gather mapped nested entities.
final List values = new ArrayList<>();
// Loop over the collection.
assert elementMapper != null;
for (final Object elt : collection) {
final T value = elementMapper.fromDb(elt);
if (value != null) {
values.add(value);
}
}
return values;
}
@Nullable
@Override
public List