001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.commons.crypto.stream.output;
019
020import java.io.IOException;
021import java.nio.ByteBuffer;
022import java.nio.channels.WritableByteChannel;
023
024/**
025 * The ChannelOutput class takes a {@code WritableByteChannel} object and
026 * wraps it as {@code Output} object acceptable by
027 * {@code CryptoOutputStream} as the output target.
028 */
029public class ChannelOutput implements Output {
030
031    private final WritableByteChannel channel;
032
033    /**
034     * Constructs a
035     * {@link org.apache.commons.crypto.stream.output.ChannelOutput}.
036     *
037     * @param channel the WritableByteChannel object.
038     */
039    public ChannelOutput(final WritableByteChannel channel) {
040        this.channel = channel;
041    }
042
043    /**
044     * Overrides the
045     * {@link org.apache.commons.crypto.stream.output.Output#write(ByteBuffer)}.
046     * Writes a sequence of bytes to this output from the given buffer.
047     *
048     * @param src The buffer from which bytes are to be retrieved.
049     *
050     * @return The number of bytes written, possibly zero.
051     * @throws IOException if an I/O error occurs.
052     */
053    @Override
054    public int write(final ByteBuffer src) throws IOException {
055        return channel.write(src);
056    }
057
058    /**
059     * Overrides the {@link Output#flush()}. Flushes this output and forces any
060     * buffered output bytes to be written out if the under layer output method
061     * support.
062     *
063     * @throws IOException if an I/O error occurs.
064     */
065    @Override
066    public void flush() throws IOException {
067        // noop
068    }
069
070    /**
071     * Overrides the {@link Output#close()}. Closes this output and releases any
072     * system resources associated with the under layer output.
073     *
074     * @throws IOException if an I/O error occurs.
075     */
076    @Override
077    public void close() throws IOException {
078        channel.close();
079    }
080}