package org.xnio.sasl;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.xnio.Buffers;
import org.xnio.conduits.AbstractMessageSinkConduit;
import org.xnio.conduits.Conduits;
import org.xnio.conduits.MessageSinkConduit;
public final class SaslUnwrappingConduit extends AbstractMessageSinkConduit<MessageSinkConduit> implements MessageSinkConduit {
private final SaslWrapper wrapper;
private ByteBuffer buffer;
public SaslUnwrappingConduit(final MessageSinkConduit next, final SaslWrapper wrapper) {
super(next);
this.wrapper = wrapper;
}
public boolean send(final ByteBuffer src) throws IOException {
if (! doSend()) {
return false;
}
ByteBuffer wrapped = ByteBuffer.wrap(wrapper.unwrap(src));
if (! next.send(wrapped)) {
buffer = wrapped;
}
return true;
}
public boolean send(final ByteBuffer[] srcs, final int offs, final int len) throws IOException {
if (! doSend()) {
return false;
}
final byte[] bytes = Buffers.take(srcs, offs, len);
final ByteBuffer wrapped = ByteBuffer.wrap(wrapper.unwrap(bytes));
if (! next.send(wrapped)) {
this.buffer = wrapped;
}
return true;
}
@Override
public boolean sendFinal(ByteBuffer src) throws IOException {
return Conduits.sendFinalBasic(this, src);
}
@Override
public boolean sendFinal(ByteBuffer[] srcs, int offs, int len) throws IOException {
return Conduits.sendFinalBasic(this, srcs, offs, len);
}
private boolean doSend() throws IOException {
final ByteBuffer buffer = this.buffer;
if (buffer != null && next.send(buffer)) {
this.buffer = null;
return true;
}
return false;
}
public boolean flush() throws IOException {
return doSend() && next.flush();
}
}