    001package org.apache.commons.ssl.asn1;
    002
    003import java.io.IOException;
    004
    005/** DER UTF8String object. */
    006public class DERUTF8String
    007    extends ASN1Object
    008    implements DERString {
    009    String string;
    010
    011    /**
    012     * return an UTF8 string from the passed in object.
    013     *
    014     * @throws IllegalArgumentException if the object cannot be converted.
    015     */
    016    public static DERUTF8String getInstance(Object obj) {
    017        if (obj == null || obj instanceof DERUTF8String) {
    018            return (DERUTF8String) obj;
    019        }
    020
    021        if (obj instanceof ASN1OctetString) {
    022            return new DERUTF8String(((ASN1OctetString) obj).getOctets());
    023        }
    024
    025        if (obj instanceof ASN1TaggedObject) {
    026            return getInstance(((ASN1TaggedObject) obj).getObject());
    027        }
    028
    029        throw new IllegalArgumentException("illegal object in getInstance: "
    030                                           + obj.getClass().getName());
    031    }
    032
    033    /**
    034     * return an UTF8 String from a tagged object.
    035     *
    036     * @param obj      the tagged object holding the object we want
    037     * @param explicit true if the object is meant to be explicitly tagged false
    038     *                 otherwise.
    039     * @throws IllegalArgumentException if the tagged object cannot be converted.
    040     */
    041    public static DERUTF8String getInstance(
    042        ASN1TaggedObject obj,
    043        boolean explicit) {
    044        return getInstance(obj.getObject());
    045    }
    046
    047    /** basic constructor - byte encoded string. */
    048    DERUTF8String(byte[] string) {
    049        this.string = Strings.fromUTF8ByteArray(string);
    050    }
    051
    052    /** basic constructor */
    053    public DERUTF8String(String string) {
    054        this.string = string;
    055    }
    056
    057    public String getString() {
    058        return string;
    059    }
    060
    061    public String toString() {
    062        return string;
    063    }
    064
    065    public int hashCode() {
    066        return this.getString().hashCode();
    067    }
    068
    069    boolean asn1Equals(DERObject o) {
    070        if (!(o instanceof DERUTF8String)) {
    071            return false;
    072        }
    073
    074        DERUTF8String s = (DERUTF8String) o;
    075
    076        return this.getString().equals(s.getString());
    077    }
    078
    079    void encode(DEROutputStream out)
    080        throws IOException {
    081        out.writeEncoded(UTF8_STRING, Strings.toUTF8ByteArray(string));
    082    }
    083}