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 */
017package org.apache.camel.impl;
018
019import java.io.InputStream;
020import java.io.OutputStream;
021import java.util.zip.GZIPInputStream;
022import java.util.zip.GZIPOutputStream;
023
024import org.apache.camel.Exchange;
025import org.apache.camel.converter.stream.OutputStreamBuilder;
026import org.apache.camel.spi.DataFormat;
027import org.apache.camel.spi.DataFormatName;
028import org.apache.camel.util.IOHelper;
029
030/**
031 * GZip {@link org.apache.camel.spi.DataFormat} for reading/writing data using gzip.
032 */
033public class GzipDataFormat extends org.apache.camel.support.ServiceSupport implements DataFormat, DataFormatName {
034
035    @Override
036    public String getDataFormatName() {
037        return "gzip";
038    }
039
040    public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception {
041        InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph);
042
043        GZIPOutputStream zipOutput = new GZIPOutputStream(stream);
044        try {
045            IOHelper.copy(is, zipOutput);
046        } finally {
047            // must close all input streams
048            IOHelper.close(is, zipOutput);
049        }
050    }
051
052    public Object unmarshal(final Exchange exchange, final InputStream inputStream) throws Exception {
053        GZIPInputStream unzipInput = null;
054
055        OutputStreamBuilder osb = OutputStreamBuilder.withExchange(exchange);
056        try {
057            unzipInput = new GZIPInputStream(inputStream);
058            IOHelper.copy(unzipInput, osb);
059            return osb.build();
060        } finally {
061            // must close all input streams
062            IOHelper.close(osb, unzipInput, inputStream);
063        }
064    }
065
066    @Override
067    protected void doStart() throws Exception {
068        // noop
069    }
070
071    @Override
072    protected void doStop() throws Exception {
073        // noop
074    }
075}