TradePurpose.java

package com.tradecloud.domain.model.deal;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.*;

@Embeddable
public class TradePurpose implements Serializable {

    public static final TradePurpose IMPORT = new TradePurpose("IMPORT");
    public static final TradePurpose EXPORT = new TradePurpose("EXPORT");

    private static List<TradePurpose> tradePurposes = new ArrayList<TradePurpose>();

    static {
        tradePurposes.add(IMPORT);
        tradePurposes.add(EXPORT);
    }

    @Column(name = "trade_purpose")
    private String code;

    private static final Map<String, TradePurpose> lookup = new HashMap<String, TradePurpose>();
    private static final String options;

    static {
        StringBuilder optionsString = new StringBuilder();
        for (TradePurpose d : tradePurposes) {
            lookup.put(d.getCode(), d);
            optionsString.append(d.getCode()).append(",");
        }

        options = optionsString.toString().substring(0, optionsString.toString().length() - 1);
    }

    public TradePurpose(String code) {
        this.code = code;
    }

    // just for hibernate
    @Deprecated
    public TradePurpose() {

    }

    public String getCode() {
        return code;
    }

    public static TradePurpose get(String key) {
        if (key != null) {
            key = key.toUpperCase();
        }
        TradePurpose tradePurpose = lookup.get(key);
        if (tradePurpose == null) {
            throw new IllegalArgumentException("Incorrect key Used for Trading Purpose : Options are " + options + " but got " + key);
        }
        return tradePurpose;
    }

    @Override
    public String toString() {
        return code;
    }

    public static Collection<String> allAsStrings() {
        return lookup.keySet();
    }
}