/********************************************************************
 * Copyright © 2004 VHA. All rights reserved
 ********************************************************************/
// Package
package gov.va.med.fw.report;

// Java classes
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

// Library classes
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.Validate;

// Framework classes
import gov.va.med.fw.service.AbstractComponent;
import gov.va.med.fw.util.FileUtils;

/**
 * Persists a generated report stream onto a file system 
 *
 * Project: Framework</br>
 * Created on: 3:46:42 PM </br>
 *
 * @author DNS   LEV
 */
public class FileSystemReportPersister extends AbstractComponent implements ReportPersister {

	/**
	 * An instance of serialVersionUID
	 */
	private static final long serialVersionUID = -878185413664735720L;

	/**
	 * A default constructor
	 */
	public FileSystemReportPersister() {
		super();
	}

	/**
	 * @see gov.va.med.fw.report.ReportPersister#persist(gov.va.med.fw.report.ReportConfiguration, java.io.ByteArrayOutputStream)
	 */
	public void persist( ReportConfiguration config, ByteArrayOutputStream stream ) throws ReportException {

		Validate.notNull( config, "A report configuration must not be NULL" );
		Validate.notNull( stream, "A report stream must not be NULL" );
		OutputStream output = null;
		try {
			String outputFile = config.getReportOutputName();
			output =  new BufferedOutputStream( FileUtils.getOutputStream( outputFile ) );
			stream.writeTo( output );
			
			// FLush contents to an output stream
			stream.flush();
			stream.close();
			
			// Flust contents in an output stream and close a stream
			output.flush();
		} catch( IOException e ) {
			throw new ReportException( "Failed to write a report to a stream ", e );
		} finally {
			if (output != null) {
				IOUtils.closeQuietly(output);
			}
		}
	}
}