Package org.raist.config

Source Code of org.raist.config.EnumSerializer

/*
* Copyright 2013 Lei CHEN (raistlic@gmail.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 org.raist.config;

import org.raist.common.codec.Codec;
import org.raist.common.codec.CodingException;

import java.util.HashMap;
import java.util.Map;

/**
* This is a factory class, which exports codecs of specified {@code enum} source
* type and the destination type of {@code String}.
*
* @author Lei.C (2013-11-04)
*/
public class EnumSerializer<E extends Enum<E>> implements Codec<E, String> {

  /**
   * This method exports a {@link Codec} instance of the specified {@code enum}
   * type and the destination type of {@link String}.
   *
   * @throws IllegalArgumentException if the specified {@code enum} type is {@code null}.
   */
  public static <E extends Enum<E>> EnumSerializer<E> of(Class<E> type) {

    if( type == null )
      throw new IllegalArgumentException("Specifiec enum type cannot be null.");

    return new EnumSerializer(type);
  }

  /*
   * The enum type reference, which provides the type context information at
   * both compile time and run time, cannot be null.
   */
  private final Class<E> type;

  private final Map<String, E> map;

  private EnumSerializer(Class<E> type) {

    assert type != null;

    this.type = type;
    this.map = new HashMap<String, E>();
    for(E e : type.getEnumConstants())
      map.put(e.name(), e);
  }

  @Override
  public boolean isValidSrc(E src) {

    return true;
  }

  @Override
  public String encode(E src) throws CodingException {

    return src == null ? "" : src.name();
  }

  @Override
  public boolean isValidDest(String dest) {

    if( dest == null || dest.isEmpty() ) {

      return true;
    }
    else {

      return map.containsKey(dest);
    }
  }

  @Override
  public E decode(String dest) throws CodingException {

    if( dest == null || dest.isEmpty() )
      return null;

    E result = map.get(dest);
    if( result == null )
      throw new CodingException(type.getSimpleName() + " not found: " + dest);

    return result;
  }
}
TOP

Related Classes of org.raist.config.EnumSerializer

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.