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

io.micronaut.configuration.rabbitmq.bind.RabbitHeaderConvertibleValues Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2017-2020 original authors
 *
 * 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 io.micronaut.configuration.rabbitmq.bind;

import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.convert.ConversionError;
import io.micronaut.core.convert.ConversionService;
import io.micronaut.core.convert.value.ConvertibleValues;

import java.util.*;

/**
 * Converts RabbitMQ header values to the requested type.
 *
 * @author James Kleeh
 * @since 1.1.0
 */
public class RabbitHeaderConvertibleValues implements ConvertibleValues {

    private final Map headers;
    private final ConversionService conversionService;
    private final List conversionErrors = new ArrayList<>();

    /**
     * Default constructor.
     *
     * @param headers The RabbitMQ headers
     * @param conversionService The conversion service
     */
    public RabbitHeaderConvertibleValues(Map headers, ConversionService conversionService) {
        this.headers = headers == null ? Collections.emptyMap() : headers;
        this.conversionService = conversionService;
    }

    @Override
    public Set names() {
        return headers.keySet();
    }

    @Override
    public Collection values() {
        return headers.values();
    }

    @Override
    public  Optional get(CharSequence name, ArgumentConversionContext conversionContext) {
        Object value = headers.get(name.toString());
        if (value != null) {
            Optional converted = conversionService.convert(value.toString(), conversionContext);
            conversionContext.getLastError().ifPresent(conversionErrors::add);
            return converted;
        }
        return Optional.empty();
    }

    /**
     * @return Any conversion errors that may have occurred
     */
    public List getConversionErrors() {
        return conversionErrors;
    }
}