All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.relaysoft.commons.data.streams.DataTeeOutputStream Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package net.relaysoft.commons.data.streams;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.Lock;

import org.apache.commons.io.output.TeeOutputStream;

import net.relaysoft.commons.data.DataID;
import net.relaysoft.commons.data.manager.DataManager;

/**
 * Tee output stream into data's content. This output stream is used when data is persistent and cached at the same time.
 * 
 * @author relaysoft.net
 *
 */
public class DataTeeOutputStream extends TeeOutputStream {
	
	private Lock lock;
	
	private boolean closed = false;
	
	/**
	 * Create new data tee output stream instance.
	 * 
	 * @param out - Main output stream to write
	 * @param branch - Secondary branch output stream to write
	 * @param dataID - Data ID for the data
	 * @param dataManager - Used data manager instance
	 * @param lock - Write lock for the data
	 * @throws TimeoutException If write lock is not acquired within one minute. 
	 * @throws InterruptedException If stream is interrupted while trying to acquire write lock. 
	 */
	public DataTeeOutputStream(OutputStream out, OutputStream branch, DataID dataID, DataManager dataManager, Lock lock) 
			throws TimeoutException, InterruptedException {
		super(out, branch);
		this.lock = lock;
		if(!this.lock.tryLock(1, TimeUnit.MINUTES)){
			throw new TimeoutException("Could not create output stream. Data content was locked by another thread.");
		}
		if(!dataID.isCompositeData() && dataManager.getDataSize(dataID) > 0){
			throw new UnsupportedOperationException("Could not create output stream. Data already has content and cannot be "
						+ "overwritten");
		}
	}

	@Override
	public void close() throws IOException {
		try{
			super.close();
		} finally {
			if(lock != null){
				lock.unlock();
			}
			closed = true;
		}
	}
	
	@Override
	protected void finalize() throws Throwable {
		if(!closed){
			close();
		}
		super.finalize();
	}

}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy