All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.datastax.driver.extras.codecs.jdk8.OptionalCodec Maven / Gradle / Ivy

There is a newer version: 3.11.5
Show newest version
/*
 *      Copyright (C) 2012-2015 DataStax Inc.
 *
 *   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.datastax.driver.extras.codecs.jdk8;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;

import com.google.common.reflect.TypeParameter;
import com.google.common.reflect.TypeToken;

import com.datastax.driver.core.TypeCodec;
import com.datastax.driver.extras.codecs.MappingCodec;

/**
 * A codec that wraps other codecs around JDK 8's {@link Optional} API.
 *
 * @param  The wrapped Java type
 */
public class OptionalCodec extends MappingCodec, T> {

    private final Predicate isAbsent;

    public OptionalCodec(TypeCodec codec) {
        this(codec, new Predicate() {
            @Override
            public boolean test(T input) {
                return input == null
                    || input instanceof Collection && ((Collection)input).isEmpty()
                    || input instanceof Map && ((Map)input).isEmpty();

            }
        });
    }

    public OptionalCodec(TypeCodec codec, Predicate isAbsent) {
        super(codec, new TypeToken>(){}.where(new TypeParameter(){}, codec.getJavaType()));
        this.isAbsent = isAbsent;
    }

    @Override
    protected Optional deserialize(T value) {
        return isAbsent(value) ? Optional.empty() : Optional.of(value);
    }

    @Override
    protected T serialize(Optional value) {
        return value.isPresent() ? value.get() : absentValue();
    }

    protected T absentValue() {
        return null;
    }

    protected boolean isAbsent(T value) {
        return isAbsent.test(value);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy