001/*
002 * JPPF.
003 * Copyright (C) 2005-2016 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    
048    write(new byte[] { (byte) b }, 0, 1);
049  }
050
051  @Override
052  public void write(final byte[] data) throws IOException {
053    write(data, 0, data.length);
054  }
055
056  @Override
057  public void write(final byte[] data, final int offset, final int len) throws IOException {
058    ByteBuffer tmpBuffer = null;
059    try {
060      tmpBuffer = DirectBufferPool.provideBuffer();
061      int cap = tmpBuffer.capacity();
062      boolean end = false;
063      int count = 0;
064      while (count < len) {
065        tmpBuffer.clear();
066        int size = Math.min(cap, len - count);
067        tmpBuffer.put(data, offset + count, size);
068        tmpBuffer.flip();
069        int n = channel.write(tmpBuffer);
070        if (n < 0) break;
071        count += n;
072      }
073    } finally {
074      if (tmpBuffer != null) {
075        DirectBufferPool.releaseBuffer(tmpBuffer);
076        tmpBuffer = null;
077      }
078    }
079  }
080}