KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > h2 > compress > CompressDeflate


1 /*
2  * Copyright 2004-2006 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html).
3  * Initial Developer: H2 Group
4  */

5 package org.h2.compress;
6 import java.sql.SQLException JavaDoc;
7 import java.util.StringTokenizer JavaDoc;
8 import java.util.zip.*;
9
10 import org.h2.message.Message;
11
12 public class CompressDeflate implements Compresser {
13     
14     private int level = Deflater.BEST_SPEED;
15     private int strategy = Deflater.DEFAULT_STRATEGY;
16     
17     public void setOptions(String JavaDoc options) throws SQLException JavaDoc {
18         if(options == null) {
19             return;
20         }
21         try {
22             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(options);
23             while(tokenizer.hasMoreElements()) {
24                 String JavaDoc option = tokenizer.nextToken();
25                 if(option.equals("level") || option.equals("l")) {
26                     level = Integer.parseInt(tokenizer.nextToken());
27                 } else if(option.equals("strategy") || option.equals("s")) {
28                     strategy = Integer.parseInt(tokenizer.nextToken());
29                 }
30             }
31         } catch(Exception JavaDoc e) {
32             throw Message.getSQLException(Message.UNSUPPORTED_COMPRESSION_OPTIONS_1, options);
33         }
34     }
35     
36     public int compress(byte[] in, int inLen, byte[] out, int outPos) {
37         Deflater deflater = new Deflater(level);
38         deflater.setStrategy(strategy);
39         deflater.setInput(in, 0, inLen);
40         deflater.finish();
41         int compressed = deflater.deflate(out, outPos, out.length - outPos);
42         return compressed;
43     }
44
45     public int getAlgorithm() {
46         return Compresser.DEFLATE;
47     }
48
49     public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos, int outLen) throws DataFormatException {
50         Inflater decompresser = new Inflater();
51         decompresser.setInput(in, inPos, inLen);
52         decompresser.finished();
53         decompresser.inflate(out, outPos, outLen);
54         decompresser.end();
55     }
56
57 }
58
Popular Tags