Example usage for java.nio.channels WritableByteChannel write

List of usage examples for java.nio.channels WritableByteChannel write

Introduction

In this page you can find the example usage for java.nio.channels WritableByteChannel write.

Prototype

public int write(ByteBuffer src) throws IOException;

Source Link

Document

Writes a sequence of bytes to this channel from the given buffer.

Usage

From source file:org.geoserver.rest.util.IOUtils.java

/**
 * Copies the content of the source channel onto the destination channel.
 * //from ww  w. j a va 2 s  .c  o m
 * @param bufferSize size of the temp buffer to use for this copy.
 * @param source the source {@link ReadableByteChannel}.
 * @param destination the destination {@link WritableByteChannel};.
 * @throws IOException in case something bad happens.
 */
public static void copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
        throws IOException {

    inputNotNull(source, destination);
    if (!source.isOpen() || !destination.isOpen())
        throw new IllegalStateException("Source and destination channels must be open.");

    final java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocateDirect(bufferSize);
    while (source.read(buffer) != -1) {
        //prepare the buffer for draining
        buffer.flip();

        //write to destination
        while (buffer.hasRemaining())
            destination.write(buffer);

        //clear
        buffer.clear();

    }

}

From source file:backtype.storm.utils.Utils.java

public static void downloadFromMaster(Map conf, String file, String localFile) throws IOException, TException {
    WritableByteChannel out = null;
    NimbusClient client = null;//ww w . j  a  v a 2  s  .  c  o m
    try {
        client = NimbusClient.getConfiguredClient(conf, 10 * 1000);
        String id = client.getClient().beginFileDownload(file);
        out = Channels.newChannel(new FileOutputStream(localFile));
        while (true) {
            ByteBuffer chunk = client.getClient().downloadChunk(id);
            int written = out.write(chunk);
            if (written == 0) {
                client.getClient().finishFileDownload(id);
                break;
            }
        }
    } finally {
        if (out != null)
            out.close();
        if (client != null)
            client.close();
    }
}

From source file:org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart.java

/**
 * Copy the ByteBuffer containing this part's binary data
 * to an output stream./*from   ww  w .j a  v a 2s  . com*/
 * 
 * @param out
 * @throws IOException
 */
public void writeDataToOutputStream(OutputStream out) throws IOException {

    ByteBuffer buf = this.getBuffer();
    buf.rewind();

    // Fix for https://github.com/plutext/docx4j/issues/80
    // from http://stackoverflow.com/questions/579600/how-to-put-the-content-of-a-bytebuffer-into-an-outputstream
    WritableByteChannel channel = Channels.newChannel(out);
    channel.write(buf);
    buf.rewind();

}

From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java

/**
 * Assign this payload to the given {@link HttpOutputMessage}.
 * @param message the message to assign this payload to
 * @throws IOException in case of I/O errors
 *///from  w  w w.  j av a 2 s .com
public void assignTo(HttpOutputMessage message) throws IOException {
    Assert.notNull(message, "Message must not be null");
    HttpHeaders headers = message.getHeaders();
    headers.setContentLength(this.data.remaining());
    headers.add(SEQ_HEADER, Long.toString(getSequence()));
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    WritableByteChannel body = Channels.newChannel(message.getBody());
    while (this.data.hasRemaining()) {
        body.write(this.data);
    }
    body.close();
}

From source file:com.bennavetta.appsite.file.ResourceService.java

private void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize.get());
    while (src.read(buffer) != -1 || buffer.position() != 0) {
        buffer.flip();//from ww  w. j  av  a 2s.  c o m
        dest.write(buffer);
        buffer.compact();
    }
}

From source file:org.springframework.boot.devtools.tunnel.payload.HttpTunnelPayload.java

/**
 * Write the content of this payload to the given target channel.
 * @param channel the channel to write to
 * @throws IOException in case of I/O errors
 *//*from   ww w.  ja v a 2  s  . c  o  m*/
public void writeTo(WritableByteChannel channel) throws IOException {
    Assert.notNull(channel, "Channel must not be null");
    while (this.data.hasRemaining()) {
        channel.write(this.data);
    }
}

From source file:org.mycore.common.content.util.MCRServletContentHelper.java

private static long copyChannel(final ReadableByteChannel src, final WritableByteChannel dest,
        final int bufferSize) throws IOException {
    if (src instanceof FileChannel) {
        return copyFileChannel((FileChannel) src, dest, bufferSize);
    }//w w w.  j  av  a 2  s . c  o m
    long bytes = 0;
    final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
    while (src.read(buffer) != -1) {
        // prepare the buffer to be drained
        buffer.flip();

        // write to the channel, may block
        bytes += dest.write(buffer);
        // If partial transfer, shift remainder down
        // If buffer is empty, same as doing clear()
        buffer.compact();
    }
    // EOF will leave buffer in fill state
    buffer.flip();
    // make sure the buffer is fully drained.
    while (buffer.hasRemaining()) {
        bytes += dest.write(buffer);
    }
    return bytes;
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private void copyChannel(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

    while (src.read(buffer) != -1) {
        buffer.flip();//from ww  w .  ja va2  s . c  o m
        dest.write(buffer);
        buffer.compact();
    }

    buffer.flip();

    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:com.taobao.adfs.distributed.rpc.Server.java

/**
 * This is a wrapper around {@link WritableByteChannel#write(ByteBuffer)}. If the amount of data is large, it writes
 * to channel in smaller chunks. This is to avoid jdk from creating many direct buffers as the size of buffer
 * increases. This also minimizes extra copies in NIO layer as a result of multiple write operations required to write
 * a large buffer.//w w  w. jav  a  2s. c o  m
 * 
 * @see WritableByteChannel#write(ByteBuffer)
 */
private static int channelWrite(WritableByteChannel channel, ByteBuffer buffer) throws IOException {

    return (buffer.remaining() <= NIO_BUFFER_LIMIT) ? channel.write(buffer) : channelIO(null, channel, buffer);
}

From source file:com.bittorrent.mpetazzoni.tracker.TrackerService.java

/**
 * Write a {@link HTTPTrackerErrorMessage} to the response with the given
 * HTTP status code./*  www .j  av  a  2s  .com*/
 *
 * @param response The HTTP response object.
 * @param body The response output stream to write to.
 * @param status The HTTP status code to return.
 * @param error The error reported by the tracker.
 */
private void serveError(Response response, OutputStream body, Status status, HTTPTrackerErrorMessage error)
        throws IOException {
    response.setCode(status.getCode());
    response.setText(status.getDescription());
    logger.warn("Could not process announce request ({}) !", error.getReason());

    WritableByteChannel channel = Channels.newChannel(body);
    channel.write(error.getData());
}