|
| 1 | +package com.dbschema.codec.jbiginteger; |
| 2 | + |
| 3 | +import com.datastax.driver.core.DataType; |
| 4 | +import com.datastax.driver.core.ProtocolVersion; |
| 5 | +import com.datastax.driver.core.TypeCodec; |
| 6 | +import com.datastax.driver.core.exceptions.InvalidTypeException; |
| 7 | + |
| 8 | +import java.math.BigDecimal; |
| 9 | +import java.nio.ByteBuffer; |
| 10 | + |
| 11 | +/** |
| 12 | + * @author Liudmila Kornilova |
| 13 | + **/ |
| 14 | +public class LongCodec extends TypeCodec<BigDecimal> { |
| 15 | + public static final LongCodec INSTANCE = new LongCodec(); |
| 16 | + |
| 17 | + private LongCodec() { |
| 18 | + super(DataType.bigint(), BigDecimal.class); |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public ByteBuffer serialize(BigDecimal value, ProtocolVersion protocolVersion) throws InvalidTypeException { |
| 23 | + if (value == null) return null; |
| 24 | + ByteBuffer bb = ByteBuffer.allocate(8); |
| 25 | + try { |
| 26 | + long l = value.longValueExact(); |
| 27 | + bb.putLong(l); |
| 28 | + } catch (ArithmeticException e) { |
| 29 | + throw new InvalidTypeException("BigInteger value " + value + " does not fit into cql type long", e); |
| 30 | + } |
| 31 | + bb.flip(); |
| 32 | + return bb; |
| 33 | + } |
| 34 | + |
| 35 | + @Override |
| 36 | + public BigDecimal deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException { |
| 37 | + return bytes == null || bytes.remaining() == 0 ? null : deserializeNoBoxing(bytes); |
| 38 | + } |
| 39 | + |
| 40 | + private BigDecimal deserializeNoBoxing(ByteBuffer bytes) { |
| 41 | + if (bytes.remaining() != 8) { |
| 42 | + throw new InvalidTypeException("Invalid value, expecting 8 bytes but got " + bytes.remaining()); |
| 43 | + } |
| 44 | + return new BigDecimal(Long.toString(bytes.getLong())); |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public BigDecimal parse(String value) throws InvalidTypeException { |
| 49 | + try { |
| 50 | + return value == null || value.isEmpty() || value.equalsIgnoreCase("NULL") |
| 51 | + ? null |
| 52 | + : new BigDecimal(value); |
| 53 | + } catch (NumberFormatException e) { |
| 54 | + throw new InvalidTypeException( |
| 55 | + String.format("Cannot parse 64-bits long value from \"%s\"", value)); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public String format(BigDecimal value) throws InvalidTypeException { |
| 61 | + if (value == null) return "NULL"; |
| 62 | + return Long.toString(value.longValue()); |
| 63 | + } |
| 64 | +} |
0 commit comments