01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.compress;
07:
08: import java.sql.SQLException;
09: import java.util.StringTokenizer;
10: import java.util.zip.DataFormatException;
11: import java.util.zip.Deflater;
12: import java.util.zip.Inflater;
13:
14: import org.h2.constant.ErrorCode;
15: import org.h2.message.Message;
16:
17: /**
18: * This is a wrapper class for the Deflater class.
19: * This algorithm supports the following options:
20: * <ul>
21: * <li>l or level: -1 (default), 0 (no compression),
22: * 1 (best speed), ..., 9 (best compression)
23: * </li><li>s or strategy: 0 (default),
24: * 1 (filtered), 2 (huffman only)
25: * </li></ul>
26: * See also java.util.zip.Deflater for details.
27: */
28: public class CompressDeflate implements Compressor {
29:
30: private int level = Deflater.DEFAULT_COMPRESSION;
31: private int strategy = Deflater.DEFAULT_STRATEGY;
32:
33: public void setOptions(String options) throws SQLException {
34: if (options == null) {
35: return;
36: }
37: try {
38: StringTokenizer tokenizer = new StringTokenizer(options);
39: while (tokenizer.hasMoreElements()) {
40: String option = tokenizer.nextToken();
41: if ("level".equals(option) || "l".equals(option)) {
42: level = Integer.parseInt(tokenizer.nextToken());
43: } else if ("strategy".equals(option)
44: || "s".equals(option)) {
45: strategy = Integer.parseInt(tokenizer.nextToken());
46: }
47: Deflater deflater = new Deflater(level);
48: deflater.setStrategy(strategy);
49: }
50: } catch (Exception e) {
51: throw Message.getSQLException(
52: ErrorCode.UNSUPPORTED_COMPRESSION_OPTIONS_1,
53: options);
54: }
55: }
56:
57: public int compress(byte[] in, int inLen, byte[] out, int outPos) {
58: Deflater deflater = new Deflater(level);
59: deflater.setStrategy(strategy);
60: deflater.setInput(in, 0, inLen);
61: deflater.finish();
62: int compressed = deflater.deflate(out, outPos, out.length
63: - outPos);
64: return compressed;
65: }
66:
67: public int getAlgorithm() {
68: return Compressor.DEFLATE;
69: }
70:
71: public void expand(byte[] in, int inPos, int inLen, byte[] out,
72: int outPos, int outLen) throws SQLException {
73: Inflater decompresser = new Inflater();
74: decompresser.setInput(in, inPos, inLen);
75: decompresser.finished();
76: try {
77: decompresser.inflate(out, outPos, outLen);
78: } catch (DataFormatException e) {
79: throw Message.getSQLException(ErrorCode.COMPRESSION_ERROR,
80: null, e);
81: }
82: decompresser.end();
83: }
84:
85: }
|