RepositorySyncOutputStream.java

/*
 * Copyright 2018 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.filerepository.service.ftp;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * The Class RepositorySyncOutputStream.
 */
public abstract class RepositorySyncOutputStream extends BufferedOutputStream {

	/** The one shot. */
	private final AtomicBoolean oneShot = new AtomicBoolean(true);

	/**
	 * Instantiates a new repository sync output stream.
	 *
	 * @param out the out
	 */
	public RepositorySyncOutputStream(final OutputStream out) {
		super(out);
	}

	/*
	 * (non-Javadoc)
	 * @see java.io.BufferedOutputStream#flush()
	 */
	@Override
	public synchronized void flush() throws IOException {
		super.flush();
	}

	/*
	 * (non-Javadoc)
	 * @see java.io.FilterOutputStream#close()
	 */
	@Override
	public void close() throws IOException {
		try {
			super.close();
			if (oneShot.getAndSet(false)) {
				synchronizeWithRepository();
			}
		} finally {
			cleanup();
		}
	}

	/**
	 * Cleanup.
	 *
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected abstract void cleanup() throws IOException;

	/**
	 * Synchronize with repository.
	 *
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	protected abstract void synchronizeWithRepository() throws IOException;
}