001/* -*- mode: Java; c-basic-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*-
002 *
003 * Copyright © 2020 microBean™.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
014 * implied.  See the License for the specific language governing
015 * permissions and limitations under the License.
016 */
017package org.microbean.settings.converter;
018
019import java.util.AbstractMap;
020import java.util.AbstractMap.SimpleImmutableEntry;
021import java.util.LinkedHashSet;
022import java.util.Map;
023import java.util.Map.Entry;
024import java.util.Collections;
025import java.util.Set;
026import java.util.Objects;
027
028import javax.enterprise.inject.Vetoed;
029
030import org.microbean.settings.Converter;
031import org.microbean.settings.Value;
032
033@Vetoed
034public class MapConverter<K, V> implements Converter<Map<K, V>> {
035
036  private static final long serialVersionUID = 1L;
037
038  private final Converter<? extends Set<? extends Entry<? extends K, ? extends V>>> converter;
039
040  public MapConverter(final Converter<? extends Set<? extends Entry<? extends K, ? extends V>>> converter) {
041    super();
042    this.converter = Objects.requireNonNull(converter);
043  }
044
045  @Override
046  public Map<K, V> convert(final Value value) {
047    final Map<K, V> returnValue;
048    final Set<? extends Entry<? extends K, ? extends V>> entrySet = this.converter.convert(value);
049    if (entrySet == null) {
050      returnValue = null;
051    } else if (entrySet.isEmpty()) {
052      returnValue = Collections.emptyMap();
053    } else {
054      final Set<Entry<K, V>> properlyTypedEntrySet = new LinkedHashSet<>();
055      for (final Entry<? extends K, ? extends V> entry : entrySet) {
056        properlyTypedEntrySet.add(new SimpleImmutableEntry<>(entry));
057      }
058      final Set<Entry<K, V>> canonicalEntrySet = Collections.unmodifiableSet(properlyTypedEntrySet);
059      returnValue = new AbstractMap<K, V>() {
060          @Override
061          public final Set<Entry<K, V>> entrySet() {
062            return canonicalEntrySet;
063          }
064        };
065    }
066    return returnValue;
067  }
068
069}