001/* 002 * Syncany, www.syncany.org 003 * Copyright (C) 2011-2016 Philipp C. Heckel <philipp.heckel@gmail.com> 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU General Public License as published by 007 * the Free Software Foundation, either version 3 of the License, or 008 * (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU General Public License for more details. 014 * 015 * You should have received a copy of the GNU General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018package org.syncany.chunk; 019 020import java.io.IOException; 021import java.io.InputStream; 022import java.io.OutputStream; 023import java.util.Map; 024import java.util.zip.Deflater; 025import java.util.zip.GZIPInputStream; 026import java.util.zip.GZIPOutputStream; 027 028/** 029 * Implements a {@link Transformer} that transforms the input/output stream 030 * using the Gzip compression algorithm. 031 * 032 * @author Philipp C. Heckel (philipp.heckel@gmail.com) 033 */ 034public class GzipTransformer extends Transformer { 035 public static final String TYPE = "gzip"; 036 private int level; 037 038 public GzipTransformer() { 039 this(Deflater.DEFAULT_COMPRESSION, null); 040 } 041 042 public GzipTransformer(Transformer nextTransformer) { 043 this(Deflater.DEFAULT_COMPRESSION, nextTransformer); 044 } 045 046 public GzipTransformer(int level, Transformer nextTransformer) { 047 super(nextTransformer); 048 this.level = level; 049 } 050 051 @Override 052 public void init(Map<String, String> settings) throws Exception { 053 // Nothing here 054 } 055 056 @Override 057 public OutputStream createOutputStream(OutputStream out) throws IOException { 058 if (nextTransformer == null) { 059 return new GZIPOutputStreamEx(out, level); 060 } 061 else { 062 return new GZIPOutputStreamEx(nextTransformer.createOutputStream(out), level); 063 } 064 } 065 066 @Override 067 public InputStream createInputStream(InputStream in) throws IOException { 068 if (nextTransformer == null) { 069 return new GZIPInputStream(in); 070 } 071 else { 072 return new GZIPInputStream(nextTransformer.createInputStream(in)); 073 } 074 } 075 076 public static class GZIPOutputStreamEx extends GZIPOutputStream { 077 /** 078 * Level is 1-9 -- 1 being best speed, and 9 being best compression 079 */ 080 public GZIPOutputStreamEx(OutputStream out, int level) throws IOException { 081 super(out); 082 def.setLevel(level); 083 } 084 } 085 086 @Override 087 public String toString() { 088 return (nextTransformer == null) ? "Gzip" : "Gzip-"+nextTransformer; 089 } 090}