001    package org.apache.commons.ssl.asn1;
002    
003    import java.io.IOException;
004    
005    public class DERGeneralString
006        extends ASN1Object implements DERString {
007        private String string;
008    
009        public static DERGeneralString getInstance(
010            Object obj) {
011            if (obj == null || obj instanceof DERGeneralString) {
012                return (DERGeneralString) obj;
013            }
014            if (obj instanceof ASN1OctetString) {
015                return new DERGeneralString(((ASN1OctetString) obj).getOctets());
016            }
017            if (obj instanceof ASN1TaggedObject) {
018                return getInstance(((ASN1TaggedObject) obj).getObject());
019            }
020            throw new IllegalArgumentException("illegal object in getInstance: "
021                                               + obj.getClass().getName());
022        }
023    
024        public static DERGeneralString getInstance(
025            ASN1TaggedObject obj,
026            boolean explicit) {
027            return getInstance(obj.getObject());
028        }
029    
030        public DERGeneralString(byte[] string) {
031            char[] cs = new char[string.length];
032            for (int i = 0; i != cs.length; i++) {
033                cs[i] = (char) (string[i] & 0xff);
034            }
035            this.string = new String(cs);
036        }
037    
038        public DERGeneralString(String string) {
039            this.string = string;
040        }
041    
042        public String getString() {
043            return string;
044        }
045    
046        public String toString() {
047            return string;
048        }
049    
050        public byte[] getOctets() {
051            char[] cs = string.toCharArray();
052            byte[] bs = new byte[cs.length];
053            for (int i = 0; i != cs.length; i++) {
054                bs[i] = (byte) cs[i];
055            }
056            return bs;
057        }
058    
059        void encode(DEROutputStream out)
060            throws IOException {
061            out.writeEncoded(GENERAL_STRING, this.getOctets());
062        }
063    
064        public int hashCode() {
065            return this.getString().hashCode();
066        }
067    
068        boolean asn1Equals(DERObject o) {
069            if (!(o instanceof DERGeneralString)) {
070                return false;
071            }
072            DERGeneralString s = (DERGeneralString) o;
073            return this.getString().equals(s.getString());
074        }
075    }