com.adgear.anoa.read.ByteArrayReader Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of anoa-core Show documentation
Show all versions of anoa-core Show documentation
Core classes for Anoa library, which aims to be a safe, convenient and fast record
de/serialization wrapper for the Avro, Thrift and Jackson libraries, using the functional idioms
of Java 8.
The anoa-core module tries to keep upstream dependencies to a minimum.
package com.adgear.anoa.read;
import com.adgear.anoa.AnoaJacksonTypeException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.IOException;
import java.nio.ByteBuffer;
class ByteArrayReader extends AbstractReader {
@Override
protected byte[] read(JsonParser jacksonParser) throws IOException {
if (jacksonParser.getCurrentToken() == JsonToken.VALUE_STRING) {
try {
return jacksonParser.getBinaryValue();
} catch (IOException e) {
return null;
}
} else if (jacksonParser.getCurrentToken() == JsonToken.VALUE_EMBEDDED_OBJECT) {
final Object object;
try {
object = jacksonParser.getEmbeddedObject();
} catch (IOException e) {
return null;
}
if (object instanceof byte[]) {
return (byte[]) object;
} else if (object instanceof ByteBuffer) {
return ((ByteBuffer) object).array();
} else {
return null;
}
}
gobbleValue(jacksonParser);
return null;
}
@Override
protected byte[] readStrict(JsonParser jacksonParser) throws AnoaJacksonTypeException, IOException {
switch (jacksonParser.getCurrentToken()) {
case VALUE_STRING:
try {
return jacksonParser.getBinaryValue();
} catch (IOException e) {
throw new AnoaJacksonTypeException("String is not base64 encoded bytes: " + jacksonParser.getText());
}
case VALUE_EMBEDDED_OBJECT:
final Object object = jacksonParser.getEmbeddedObject();
if (object instanceof byte[]) {
return (byte[]) object;
} else if (object instanceof ByteBuffer) {
return ((ByteBuffer) object).array();
} else {
throw new AnoaJacksonTypeException("Token is not byte[]: " + jacksonParser.getCurrentToken());
}
case VALUE_NULL:
return null;
default:
throw new AnoaJacksonTypeException("Token is not string or byte[]: " + jacksonParser.getCurrentToken());
}
}
}