/*
Copyright (C) 2001, 2006 United States Government
as represented by the Administrator of the
National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind;

/**
 * @author Tom Gaskins
 * @version $Id: RetrieveToFilePostProcessor.java 510 2007-01-17 04:57:40Z ericdalgliesh $
 */
public final class RetrieveToFilePostProcessor implements RetrievalPostProcessor
{
    java.io.File destination;

    /**
     * @param destination
     * @throws IllegalArgumentException if <code>destination</code> is null
     */
    public RetrieveToFilePostProcessor(java.io.File destination)
    {
        if (destination == null)
        {
            String message = WorldWind.retrieveErrMsg("nullValue.DestNull");
            WorldWind.logger().log(java.util.logging.Level.FINE, message);
            throw new IllegalArgumentException(message);
        }

        this.destination = destination;
    }

    /**
     * @param retriever
     * @return
     * @throws IllegalArgumentException if <code>retriever</code> is null
     */
    public java.nio.ByteBuffer run(Retriever retriever)
    {
        if (retriever == null)
        {
            String message = WorldWind.retrieveErrMsg("nullValue.RetrieverIsNull");
            WorldWind.logger().log(java.util.logging.Level.FINE, message);
            throw new IllegalArgumentException(message);
        }

        try
        {
            java.nio.ByteBuffer buffer = retriever.getBuffer();
            if (buffer == null)
            {
                WorldWind.logger().log(java.util.logging.Level.FINE, WorldWind.retrieveErrMsg(
                    "RetrieveToFilePostProcessor.NullBufferPostprocessing") + retriever.getName());
                return null;
            }

            java.io.FileOutputStream fos = null;
            try
            {
                fos = new java.io.FileOutputStream(this.destination);
                fos.getChannel().write(buffer);
                return null;
            }
            catch (java.io.IOException e)
            {
                throw e;
            }
            finally
            {
                if (fos != null)
                    fos.close();
            }
        }
        catch (java.io.IOException e)
        {
            String message = WorldWind.retrieveErrMsg("RetrieveToFilePostProcessor.ErrorPostprocessing") + retriever
                .getName();
            WorldWind.logger().log(java.util.logging.Level.FINE, message);
            throw new WWRuntimeException(message, e);
        }
    }
}
