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.ByteArrayOutputStream;
020import java.io.InputStream;
021import java.io.OutputStream;
022import java.util.zip.GZIPInputStream;
023import java.util.zip.GZIPOutputStream;
024
025import org.apache.camel.Exchange;
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(Exchange exchange, Object graph, 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(Exchange exchange, InputStream stream) throws Exception {
053        InputStream is = exchange.getIn().getMandatoryBody(InputStream.class);
054        GZIPInputStream unzipInput = null;
055
056        // Create an expandable byte array to hold the inflated data
057        ByteArrayOutputStream bos = new ByteArrayOutputStream();
058        try {
059            unzipInput = new GZIPInputStream(is);
060            IOHelper.copy(unzipInput, bos);
061            return bos.toByteArray();
062        } finally {
063            // must close all input streams
064            IOHelper.close(unzipInput, is);
065        }
066    }
067
068    @Override
069    protected void doStart() throws Exception {
070        // noop
071    }
072
073    @Override
074    protected void doStop() throws Exception {
075        // noop
076    }
077}