Package decoder.primitive

Source Code of decoder.primitive.StringDecoder

package decoder.primitive;

import api.Decoder;
import api.exceptions.DecodingException;
import com.google.common.io.BaseEncoding;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
* Decodes String in HEX format
*
* @author Denis Golovachev
* @author $Author$ (current maintainer)
* @since 1.0
*/
public class StringDecoder implements Decoder<String> {

    private static final HexStringDecoder DECODER = new HexStringDecoder();
    /**
     * Наконец, значения типа string выглядят по-разному в зависимости от длины передаваемой строки L.
     * Если L <= 253, то кодируется один байт L, затем L байтов строки, затем от 0 до 3 символов с кодом 0,
     * чтобы общая длина значения делилась на 4, после чего все это интерпретируется как последовательность
     * из int(L/4)+1 32-битных чисел. Если же L>=254, то кодируется байт 254, затем — 3 байта с длиной строки L,
     * затем — L байтов строки, затем - от 0 до 3 нулевых байтов выравнивания.
     */
    @Override
    public String decode(InputStream stream) throws DecodingException {
        try {
            return hexToString(DECODER.decode(stream));
        } catch (UnsupportedEncodingException e) {
            throw new DecodingException(e);
        }
    }

    @Override
    public boolean isTypeConstructor(int otherConstructor) {
        return DECODER.isTypeConstructor(otherConstructor);
    }

    private String hexToString(String hex) throws UnsupportedEncodingException {
        return new String(BaseEncoding.base16().lowerCase().decode(hex), "UTF-8");
    }
}
TOP

Related Classes of decoder.primitive.StringDecoder

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.