io.dyn.net.nio.BufferByteChannel.java Source code

Java tutorial

Introduction

Here is the source code for io.dyn.net.nio.BufferByteChannel.java

Source

/*
 * Copyright (c) 2011-2012 by the original author or authors.
 *
 * 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 io.dyn.net.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

import org.springframework.util.Assert;

/**
 * @author Jon Brisbin <jon@jbrisbin.com>
 */
public class BufferByteChannel implements ReadableByteChannel, WritableByteChannel {

    private Buffer buffer;

    public BufferByteChannel(Buffer buffer) {
        Assert.notNull(buffer, "Buffer cannot be null.");
        this.buffer = buffer;
    }

    @Override
    public int read(ByteBuffer dst) throws IOException {
        int start = buffer.position();
        if (null != buffer.byteBuffer()) {
            dst.put(buffer.byteBuffer());
        }
        return buffer.position() - start;
    }

    @Override
    public boolean isOpen() {
        return true;
    }

    @Override
    public void close() throws IOException {

    }

    @Override
    public int write(ByteBuffer src) throws IOException {
        int start = buffer.position();
        buffer.append(src);
        return buffer.position() - start;
    }

}