Java Code Examples for java.nio.channels.WritableByteChannel#write()

The following examples show how to use java.nio.channels.WritableByteChannel#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NcStream.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static int writeVInt(WritableByteChannel wbc, int value) throws IOException {
  ByteBuffer bb = ByteBuffer.allocate(8);

  while (true) {
    if ((value & ~0x7F) == 0) {
      bb.put((byte) value);
      break;
    } else {
      bb.put((byte) ((value & 0x7F) | 0x80));
      value >>>= 7;
    }
  }

  bb.flip();
  wbc.write(bb);
  return bb.limit();
}
 
Example 2
Source File: AsyncProcessor.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
static InputStream copyRequestBody(ODataRequest request) {
  ByteArrayOutputStream buffer = new ByteArrayOutputStream();
  InputStream input = request.getBody();
  if (input != null) {
    try {
      ByteBuffer inBuffer = ByteBuffer.allocate(8192);
      ReadableByteChannel ic = Channels.newChannel(input);
      WritableByteChannel oc = Channels.newChannel(buffer);
      while (ic.read(inBuffer) > 0) {
        inBuffer.flip();
        oc.write(inBuffer);
        inBuffer.rewind();
      }
      return new ByteArrayInputStream(buffer.toByteArray());
    } catch (IOException e) {
      throw new ODataRuntimeException("Error on reading request content");
    }
  }
  return null;
}
 
Example 3
Source File: QueryMessageTransfer.java    From rocketmq_trans_message with Apache License 2.0 6 votes vote down vote up
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
    if (this.byteBufferHeader.hasRemaining()) {
        transfered += target.write(this.byteBufferHeader);
        return transfered;
    } else {
        List<ByteBuffer> messageBufferList = this.queryMessageResult.getMessageBufferList();
        for (ByteBuffer bb : messageBufferList) {
            if (bb.hasRemaining()) {
                transfered += target.write(bb);
                return transfered;
            }
        }
    }

    return 0;
}
 
Example 4
Source File: ManyMessageTransfer.java    From RocketMQ-Master-analyze with Apache License 2.0 6 votes vote down vote up
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
    if (this.byteBufferHeader.hasRemaining()) {
        transfered += target.write(this.byteBufferHeader);
        return transfered;
    }
    else {
        List<ByteBuffer> messageBufferList = this.getMessageResult.getMessageBufferList();
        for (ByteBuffer bb : messageBufferList) {
            if (bb.hasRemaining()) {
                transfered += target.write(bb);
                return transfered;
            }
        }
    }

    return 0;
}
 
Example 5
Source File: MkvElement.java    From amazon-kinesis-video-streams-parser-library with Apache License 2.0 5 votes vote down vote up
protected void writeByteBufferToChannel(ByteBuffer src, WritableByteChannel outputChannel)
        throws MkvElementVisitException {
    src.rewind();
    int size = src.remaining();
    try {
        int numBytes = outputChannel.write(src);
        Validate.isTrue(size == numBytes, "Output channel wrote " + size + " bytes instead of " + numBytes);
    } catch (IOException e) {
        throw new MkvElementVisitException("Writing to output channel failed", e);
    } finally {
        src.rewind();
    }
}
 
Example 6
Source File: GltfAssetWriterV2.java    From JglTF with MIT License 5 votes vote down vote up
/**
 * Append the given buffer to this data
 * 
 * @param buffer The buffer
 * @throws IOException If an IO error occurs
 */
void append(ByteBuffer buffer) throws IOException
{
    @SuppressWarnings("resource")
    WritableByteChannel writableByteChannel = 
        Channels.newChannel(baos);
    writableByteChannel.write(buffer.slice());
}
 
Example 7
Source File: RxFile.java    From RxFile with Apache License 2.0 5 votes vote down vote up
private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
    throws IOException {
  final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
  while (src.read(buffer) != -1) {
    buffer.flip();
    dest.write(buffer);
    buffer.compact();
  }
  buffer.flip();
  while (buffer.hasRemaining()) {
    dest.write(buffer);
  }
}
 
Example 8
Source File: BlobStoreHardDeleteTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize)
    throws IOException {
  buffer.position(messageList.get(index).position + (int) relativeOffset);
  byte[] toReturn = new byte[Math.min(messageList.get(index).size, (int) maxSize)];
  buffer.get(toReturn);
  return channel.write(ByteBuffer.wrap(toReturn));
}
 
Example 9
Source File: D2GS.java    From riiablo with Apache License 2.0 5 votes vote down vote up
public void send(Packet packet) throws IOException {
  if (!socket.isConnected()) return;
  WritableByteChannel out = Channels.newChannel(socket.getOutputStream());
  packet.buffer.mark();
  out.write(packet.buffer);
  packet.buffer.reset();
  if ((connected & (1 << id)) == 0 && packet.data.dataType() == D2GSData.Connection) {
    connected |= (1 << id);
  }
}
 
Example 10
Source File: Germ.java    From swim with Apache License 2.0 5 votes vote down vote up
public void writeValue(WritableByteChannel channel) {
  final ByteBuffer buffer = toByteBuffer();
  int k;
  try {
    do {
      k = channel.write(buffer);
    } while (k > 0 && buffer.hasRemaining());
    if (buffer.hasRemaining()) {
      throw new StoreException("wrote incomplete germ");
    }
  } catch (IOException cause) {
    throw new StoreException(cause);
  }
}
 
Example 11
Source File: FreeBox.java    From mp4parser with Apache License 2.0 5 votes vote down vote up
public void getBox(WritableByteChannel os) throws IOException {
    for (ParsableBox replacer : replacers) {
        replacer.getBox(os);
    }
    ByteBuffer header = ByteBuffer.allocate(8);
    IsoTypeWriter.writeUInt32(header, 8 + data.limit());
    header.put(TYPE.getBytes());
    ((Buffer)header).rewind();
    os.write(header);
    ((Buffer)header).rewind();
    ((Buffer)data).rewind();
    os.write(data);
    ((Buffer)data).rewind();

}
 
Example 12
Source File: GoogleCloudStorageTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void reupload_failure_cacheTooSmall_singleWrite_singleChunk() throws Exception {
  byte[] testData = new byte[MediaHttpUploader.MINIMUM_CHUNK_SIZE];
  new Random().nextBytes(testData);
  int uploadChunkSize = testData.length;
  int uploadCacheSize = testData.length / 2;

  MockHttpTransport transport =
      mockTransport(
          emptyResponse(HttpStatusCodes.STATUS_CODE_NOT_FOUND),
          resumableUploadResponse(BUCKET_NAME, OBJECT_NAME),
          jsonErrorResponse(ErrorResponses.GONE));

  AsyncWriteChannelOptions writeOptions =
      AsyncWriteChannelOptions.builder()
          .setUploadChunkSize(uploadChunkSize)
          .setUploadCacheSize(uploadCacheSize)
          .build();

  GoogleCloudStorage gcs =
      mockedGcs(GCS_OPTIONS.toBuilder().setWriteChannelOptions(writeOptions).build(), transport);

  WritableByteChannel writeChannel = gcs.create(new StorageResourceId(BUCKET_NAME, OBJECT_NAME));
  writeChannel.write(ByteBuffer.wrap(testData));

  IOException writeException = assertThrows(IOException.class, writeChannel::close);

  assertThat(writeException).hasCauseThat().isInstanceOf(GoogleJsonResponseException.class);
  assertThat(writeException).hasCauseThat().hasMessageThat().startsWith("410");
}
 
Example 13
Source File: SimpleCanalConnector.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
private void writeWithHeader(WritableByteChannel channel, byte[] body) throws IOException {
    synchronized (writeDataLock) {
        writeHeader.clear();
        writeHeader.putInt(body.length);
        writeHeader.flip();
        channel.write(writeHeader);
        channel.write(ByteBuffer.wrap(body));
    }
}
 
Example 14
Source File: MSI.java    From riiablo with Apache License 2.0 5 votes vote down vote up
private boolean StartInstance(Socket socket, com.riiablo.net.packet.msi.MSI packet) throws IOException {
  Gdx.app.debug(TAG, "Starting instance...");

  try {
    File outFile = new File("D2GS.tmp");
    ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", "server/d2gs/build/libs/d2gs-1.0.jar");
    processBuilder.redirectOutput(ProcessBuilder.Redirect.to(outFile));
    processBuilder.redirectError(ProcessBuilder.Redirect.to(outFile));
    Process process = processBuilder.start();
    instances.add(process);
  } catch (Throwable t) {
    Gdx.app.error(TAG, t.getMessage(), t);
  }

  int ip     = 2130706433; // 127.0.0.1
  short port = 6114;

  FlatBufferBuilder builder = new FlatBufferBuilder();
  StartInstance.startStartInstance(builder);
  StartInstance.addResult(builder, Result.SUCCESS);
  StartInstance.addIp(builder, ip);
  StartInstance.addPort(builder, port);
  int startInstanceOffset = StartInstance.endStartInstance(builder);
  int id = com.riiablo.net.packet.msi.MSI.createMSI(builder, MSIData.StartInstance, startInstanceOffset);
  builder.finish(id);

  ByteBuffer data = builder.dataBuffer();
  OutputStream out = socket.getOutputStream();
  WritableByteChannel channel = Channels.newChannel(out);
  channel.write(data);
  Gdx.app.debug(TAG, "Returning instance at " + InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(ip).array()));
  return true;
}
 
Example 15
Source File: MessageFormatSendTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Override
public long writeTo(int index, WritableByteChannel channel, long relativeOffset, long maxSize) throws IOException {
  buffers.get(index).position((int) relativeOffset);
  buffers.get(index).limit((int) Math.min(buffers.get(index).limit(), relativeOffset + maxSize));
  int written = channel.write(buffers.get(index));
  buffers.get(index).clear();
  return written;
}
 
Example 16
Source File: DXTImage.java    From tribaltrouble with GNU General Public License v2.0 4 votes vote down vote up
private static void writeContents(WritableByteChannel out, ByteBuffer data) throws IOException {
	while (data.hasRemaining())
		out.write(data);
}
 
Example 17
Source File: WebVttTrack.java    From mp4parser with Apache License 2.0 4 votes vote down vote up
public void writeTo(WritableByteChannel channel) throws java.io.IOException {
    channel.write(vtte.duplicate());
}
 
Example 18
Source File: SocketSendBufferPool.java    From simple-netty-source with Apache License 2.0 4 votes vote down vote up
public final long transferTo(WritableByteChannel ch) throws IOException {
    return ch.write(buffer);
}
 
Example 19
Source File: DelegatingByteBufferView.java    From bt with Apache License 2.0 4 votes vote down vote up
@Override
public int transferTo(WritableByteChannel sbc) throws IOException {
    return sbc.write(delegate);
}
 
Example 20
Source File: Util.java    From beat-link with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Writes the entire remaining contents of the buffer to the channel. May complete in one operation, but the
 * documentation is vague, so this keeps going until we are sure.
 *
 * @param buffer the data to be written
 * @param channel the channel to which we want to write data
 *
 * @throws IOException if there is a problem writing to the channel
 */
public static void writeFully(ByteBuffer buffer, WritableByteChannel channel) throws IOException {
    while (buffer.hasRemaining()) {
        channel.write(buffer);
    }
}