net.relaysoft.commons.data.streams.DataTeeOutputStream Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of data-manager Show documentation
Show all versions of data-manager Show documentation
Data management utility project
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();
}
}