I’m trying to decompress a value returned with MySQL’s COMPRESS function:
SQLQuery query = session
.createSQLQuery("SELECT ID, COMPRESS(TEXT_COL) AS TEXT_COL FROM TABLE WHERE ID IN (1,2,3,...);")
.addScalar("ID", Hibernate.INTEGER)
.addScalar("TEXT_COL", Hibernate.TEXT);
List<Object[]> list = query.list();
for (Object[] result : list) {
String text = decompress(((String) result[1]).getBytes());
}
(...)
private String decompress(byte[] bs) {
InputStream in = new InflaterInputStream(new ByteArrayInputStream(bs));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[8192];
int len;
while((len = in.read(buffer))>0)
baos.write(buffer, 0, len);
return new String(baos.toByteArray(), "UTF-8");
} catch (IOException e) {
throw new AssertionError(e);
}
}
And I’m getting java.lang.AssertionError: java.util.zip.ZipException: incorrect header check
What’s the way to decompress such mysql result or what’s wrong with my code?
Thanks in advance,
Diego.
EDIT:
Thanks to Joni for the suggestions, I finally changed the code to
SQLQuery query = session
.createSQLQuery("SELECT ID, COMPRESS(TEXT_COL) AS TEXT_COL FROM TABLE WHERE ID IN (1,2,3,...);")
.addScalar("ID", Hibernate.INTEGER)
.addScalar("TEXT_COL", Hibernate.BINARY);
List<Object[]> list = query.list();
for (Object[] result : list) {
String text = decompress(((byte[]) result[1]));
}
(...)
private String decompress(byte[] bs) {
InputStream in = new InflaterInputStream(new ByteArrayInputStream(bs, 4, bs.length-4));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[8192];
int len;
while((len = in.read(buffer))>0)
baos.write(buffer, 0, len);
return new String(baos.toByteArray(), "UTF-8");
} catch (IOException e) {
throw new AssertionError(e);
}
}
You have to skip 4 bytes in the beginning of the stream:
This is because the
COMPRESSfunction returns a string where the first four bytes give the length of compressed data and the following bytes are the actual compressed data.Also, you should try to find a way to obtain the result directly as bytes. The compressed result is binary data and probably cannot be converted safely into a String.