package org.glassfish.grizzly.streams;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.CompletionHandler;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.GrizzlyFuture;
import org.glassfish.grizzly.TransformationException;
import org.glassfish.grizzly.TransformationResult;
import org.glassfish.grizzly.TransformationResult.Status;
import org.glassfish.grizzly.Transformer;
import org.glassfish.grizzly.impl.ReadyFutureImpl;
import org.glassfish.grizzly.memory.Buffers;
public abstract class AbstractStreamWriter implements StreamWriter {
protected static final Logger logger = Grizzly.logger(AbstractStreamWriter.class);
protected static final Integer ZERO = 0;
protected static final GrizzlyFuture<Integer> ZERO_READY_FUTURE = ReadyFutureImpl.create(ZERO);
private final Connection connection;
private long timeoutMillis = 30000;
private final AtomicBoolean isClosed = new AtomicBoolean();
protected final boolean isOutputBuffered;
protected final Output output;
protected AbstractStreamWriter(final Connection connection, Output streamOutput) {
this.connection = connection;
this.output = streamOutput;
this.isOutputBuffered = streamOutput.isBuffered();
}
@Override
public GrizzlyFuture<Integer> flush() throws IOException {
return flush(null);
}
@Override
public GrizzlyFuture<Integer> flush(CompletionHandler<Integer> completionHandler) throws IOException {
return output.flush(completionHandler);
}
@Override
public boolean isClosed() {
return isClosed.get();
}
@Override
public void close() throws IOException {
close(null);
}
@Override
public GrizzlyFuture<Integer> close(CompletionHandler<Integer> completionHandler) throws IOException {
if (!isClosed.getAndSet(true)) {
return output.close(completionHandler);
}
return ReadyFutureImpl.create(0);
}
@Override
public void writeBuffer(Buffer b) throws IOException {
output.write(b);
}
@Override
public void writeBoolean(final boolean data) throws IOException {
final byte value = data ? (byte) 1 : (byte) 0;
writeByte(value);
}
@Override
public void writeByte(final byte data) throws IOException {
output.write(data);
}
@Override
public void writeChar(final char data) throws IOException {
if (isOutputBuffered) {
output.ensureBufferCapacity(2);
output.getBuffer().putChar(data);
} else {
output.write((byte) (data >>> 8 & 0xFF));
output.write((byte) (data & 0xFF));
}
}
@Override
public void writeShort(final short data) throws IOException {
if (isOutputBuffered) {
output.ensureBufferCapacity(2);
output.getBuffer().putShort(data);
} else {
output.write((byte) (data >>> 8 & 0xFF));
output.write((byte) (data & 0xFF));
}
}
@Override
public void writeInt(final int data) throws IOException {
if (isOutputBuffered) {
output.ensureBufferCapacity(4);
output.getBuffer().putInt(data);
} else {
output.write((byte) (data >>> 24 & 0xFF));
output.write((byte) (data >>> 16 & 0xFF));
output.write((byte) (data >>> 8 & 0xFF));
output.write((byte) (data & 0xFF));
}
}
@Override
public void writeLong(final long data) throws IOException {
if (isOutputBuffered) {
output.ensureBufferCapacity(8);
output.getBuffer().putLong(data);
} else {
output.write((byte) (data >>> 56 & 0xFF));
output.write((byte) (data >>> 48 & 0xFF));
output.write((byte) (data >>> 40 & 0xFF));
output.write((byte) (data >>> 32 & 0xFF));
output.write((byte) (data >>> 24 & 0xFF));
output.write((byte) (data >>> 16 & 0xFF));
output.write((byte) (data >>> 8 & 0xFF));
output.write((byte) (data & 0xFF));
}
}
@Override
public void writeFloat(final float data) throws IOException {
writeInt(Float.floatToIntBits(data));
}
@Override
public void writeDouble(final double data) throws IOException {
writeLong(Double.doubleToLongBits(data));
}
@Override
public void writeBooleanArray(final boolean[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
output.write((byte) (data[i] ? 1 : 0));
}
}
@Override
public void writeByteArray(final byte[] data) throws IOException {
writeByteArray(data, 0, data.length);
}
@Override
public void writeByteArray(byte[] data, int offset, int length) throws IOException {
final Buffer buffer = Buffers.wrap(connection.getMemoryManager(), data, offset, length);
output.write(buffer);
}
@Override
public void writeCharArray(final char[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
writeChar(data[i]);
}
}
@Override
public void writeShortArray(final short[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
writeShort(data[i]);
}
}
@Override
public void writeIntArray(final int[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
writeInt(data[i]);
}
}
@Override
public void writeLongArray(final long[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
writeLong(data[i]);
}
}
@Override
public void writeFloatArray(final float[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
writeFloat(data[i]);
}
}
@Override
public void writeDoubleArray(final double[] data) throws IOException {
for (int i = 0; i < data.length; i++) {
writeDouble(data[i]);
}
}
@Override
public <E> GrizzlyFuture<Stream> encode(Transformer<E, Buffer> encoder, E object) throws IOException {
return encode(encoder, object, null);
}
@Override
public <E> GrizzlyFuture<Stream> encode(Transformer<E, Buffer> encoder, E object, CompletionHandler<Stream> completionHandler) throws IOException {
Exception exception = null;
final TransformationResult<E, Buffer> result = encoder.transform(connection, object);
final Status status = result.getStatus();
if (status == Status.COMPLETE) {
output.write(result.getMessage());
if (completionHandler != null) {
completionHandler.completed(this);
}
return ReadyFutureImpl.<Stream>create(this);
} else if (status == Status.INCOMPLETE) {
exception = new IllegalStateException("Encoder returned INCOMPLETE state");
}
if (exception == null) {
exception = new TransformationException(result.getErrorCode() + ": " + result.getErrorDescription());
}
return ReadyFutureImpl.create(exception);
}
@Override
public Connection getConnection() {
return connection;
}
@Override
public long getTimeout(TimeUnit timeunit) {
return timeunit.convert(timeoutMillis, TimeUnit.MILLISECONDS);
}
@Override
public void setTimeout(long timeout, TimeUnit timeunit) {
timeoutMillis = TimeUnit.MILLISECONDS.convert(timeout, timeunit);
}
public static class DisposeBufferCompletionHandler implements CompletionHandler {
private final Buffer buffer;
public DisposeBufferCompletionHandler(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void cancelled() {
disposeBuffer();
}
@Override
public void failed(Throwable throwable) {
disposeBuffer();
}
@Override
public void completed(Object result) {
disposeBuffer();
}
@Override
public void updated(Object result) {
}
protected void disposeBuffer() {
buffer.dispose();
}
}
}