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

org.immutables.fixture.encoding.defs.OptionalMap Maven / Gradle / Ivy

There is a newer version: 2.10.1
Show newest version
/*
   Copyright 2016 Immutables Authors and Contributors

   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 org.immutables.fixture.encoding.defs;

import java.util.Optional;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.immutables.encode.Encoding;

@Encoding
class OptionalMap {

  // implemented as nullable map field
  @Encoding.Impl
  private final ImmutableMap map = null;

  // Expose (and detect) the field as Optional of Map
  @Encoding.Expose
  public Optional> get() {
    return Optional.>ofNullable(map);
  }

  // alternatively it can be exposed as Optional of ImmutableMap
  @Encoding.Expose
  public Optional> getImmutable() {
    return Optional.ofNullable(map);
  }

  // as field is nullable, so null-safe hashcode required
  @Override
  public int hashCode() {
    return java.util.Objects.hashCode(map);
  }

  @Override
  public String toString() {
    return get().toString();
  }

  boolean equals(OptionalMap obj) {
    return java.util.Objects.equals(this.map, obj.map);
  }

  @Encoding.Of
  static @Nullable  ImmutableMap init(Optional> map) {
    return map.isPresent()
        ? ImmutableMap.copyOf(map.get())
        : null;
  }

  @Encoding.Builder
  static class Builder {
    private @Nullable ImmutableMap.Builder builder = null;

    @Encoding.Naming("put*")
    @Encoding.Init
    void put(K row, V value) {
      nonnullBuilder().put(row, value);
    }

    @Encoding.Naming("putAll*")
    @Encoding.Init
    void putAll(Map entries) {
      nonnullBuilder().putAll(entries);
    }

    @Encoding.Naming("set*")
    @Encoding.Init
    @Encoding.Copy
    void set(Optional> entries) {
      this.builder = null;
      if (entries.isPresent()) {
        nonnullBuilder().putAll(entries.get());
      }
    }

    private ImmutableMap.Builder nonnullBuilder() {
      return builder == null ? builder = ImmutableMap.builder() : builder;
    }

    @Encoding.Build
    @Nullable
    ImmutableMap build() {
      return builder != null ? builder.build() : null;
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy