001/*
002 * JPPF.
003 * Copyright (C) 2005-2018 JPPF Team.
004 * http://www.jppf.org
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * 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 */
018
019package org.jppf.utils.streams;
020
021import java.io.*;
022import java.nio.ByteBuffer;
023import java.nio.channels.WritableByteChannel;
024
025import org.jppf.utils.pooling.DirectBufferPool;
026
027/**
028 * An {@link OutputStream} implementation that writes to an underlying {@link WritableByteChannel} which is assumed to be in <b>blocking mode</b>.
029 * @author Laurent Cohen
030 */
031public class ChannelOutputStream extends OutputStream {
032  /**
033   * The backing {@link WritableByteChannel}.
034   */
035  private final WritableByteChannel channel;
036
037  /**
038   * Initialize this output stream with the specified writeable channel.
039   * @param channel the channel to write to.
040   */
041  public ChannelOutputStream(final WritableByteChannel channel) {
042    this.channel = channel;
043  }
044
045  @Override
046  public void write(final int b) throws IOException {
047    write(new byte[] { (byte) b }, 0, 1);
048  }
049
050  @Override
051  public void write(final byte[] data) throws IOException {
052    write(data, 0, data.length);
053  }
054
055  @Override
056  public void write(final byte[] data, final int offset, final int len) throws IOException {
057    ByteBuffer tmpBuffer = null;
058    try {
059      tmpBuffer = DirectBufferPool.provideBuffer();
060      final int cap = tmpBuffer.capacity();
061      int count = 0;
062      while (count < len) {
063        tmpBuffer.clear();
064        final int size = Math.min(cap, len - count);
065        tmpBuffer.put(data, offset + count, size);
066        tmpBuffer.flip();
067        final int n = channel.write(tmpBuffer);
068        if (n < 0) break;
069        count += n;
070      }
071    } finally {
072      if (tmpBuffer != null) DirectBufferPool.releaseBuffer(tmpBuffer);
073    }
074  }
075}