001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.camel.component.http.helper; 018 019 import java.io.ByteArrayInputStream; 020 import java.io.ByteArrayOutputStream; 021 import java.io.IOException; 022 import java.io.InputStream; 023 import java.util.zip.GZIPInputStream; 024 import java.util.zip.GZIPOutputStream; 025 026 import org.apache.camel.Exchange; 027 import org.apache.camel.Message; 028 import org.apache.camel.util.ObjectHelper; 029 030 /** 031 * Helper class to help wrapping content into GZIP input and output streams. 032 */ 033 public final class GZIPHelper { 034 035 private GZIPHelper() { 036 } 037 038 public static InputStream toGZIPInputStream(String contentEncoding, InputStream in) throws IOException { 039 if (isGzip(contentEncoding)) { 040 return new GZIPInputStream(in); 041 } else { 042 return in; 043 } 044 } 045 046 public static InputStream toGZIPInputStream(String contentEncoding, byte[] data) throws Exception { 047 if (isGzip(contentEncoding)) { 048 ByteArrayOutputStream os = null; 049 GZIPOutputStream gzip = null; 050 try { 051 os = new ByteArrayOutputStream(); 052 gzip = new GZIPOutputStream(os); 053 gzip.write(data); 054 gzip.finish(); 055 return new ByteArrayInputStream(os.toByteArray()); 056 } finally { 057 ObjectHelper.close(gzip, "gzip", null); 058 ObjectHelper.close(os, "byte array", null); 059 } 060 } else { 061 return new ByteArrayInputStream(data); 062 } 063 } 064 065 public static byte[] compressGZIP(byte[] data) throws IOException { 066 ByteArrayOutputStream os = new ByteArrayOutputStream(); 067 GZIPOutputStream gzip = new GZIPOutputStream(os); 068 try { 069 gzip.write(data); 070 gzip.finish(); 071 return os.toByteArray(); 072 } finally { 073 gzip.close(); 074 os.close(); 075 } 076 } 077 078 public static boolean isGzip(Message message) { 079 return isGzip(message.getHeader(Exchange.CONTENT_ENCODING, String.class)); 080 } 081 082 public static boolean isGzip(String header) { 083 return header != null && header.toLowerCase().contains("gzip"); 084 } 085 086 }