/*
 * Copyright (c) 2002-2010 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 *  the terms of the license agreement you entered into with JSCAPE.
 */

package com.jscape.util.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import static com.jscape.util.IOTools.close;

/**
 * @author Alex Usun
 */
public class DataTools {

    @SafeVarargs
    public static <T> T read(DataSource source, DataReader<T>... readers)
            throws IOException {
        for (DataReader<T> reader : readers) {
            try {
                return read(source.getInputStream(), reader);
            } catch (Throwable e) {
                // ignore
            }
        }

        throw new IOException("Unsupported data format.");
    }

    @SafeVarargs
    public static <T> void write(T value, DataSource source, DataWriter<T>... writers)
            throws IOException {
        for (DataWriter<T> writer : writers) {
            try {
                write(value, source.getOutputStream(), writer);
                return;
            } catch (Throwable e) {
                // ignore
            }
        }

        throw new IOException("Unsupported data format.");
    }

    public static <T> T read(InputStream in, DataReader<T> reader)
            throws Exception {
        try {
            return reader.read(in);
        } finally {
            close(in);
        }
    }

    public static <T> void write(T value, OutputStream out, DataWriter<T> writer)
            throws IOException {
        try {
            writer.write(value, out);
        } finally {
            close(out);
        }
    }

    private DataTools() {
        // empty
    }
}