All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.http.WritableByteChannelSocketWriter Maven / Gradle / Ivy

/*
 * Copyright 2016 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.http;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

import br.com.objectos.io.ByteSource;

/**
 * @author [email protected] (Marcio Endo)
 */
class WritableByteChannelSocketWriter implements SocketWriter {

  private static final String NEW_LINE = "\r\n";

  private final WritableByteChannel channel;
  private final ByteBuffer buffer;

  private WritableByteChannelSocketWriter(WritableByteChannel channel, ByteBuffer buffer) {
    this.channel = channel;
    this.buffer = buffer;
  }

  public static WritableByteChannelSocketWriter of(WritableByteChannel channel, ByteBuffer buffer) {
    buffer.clear();
    return new WritableByteChannelSocketWriter(channel, buffer);
  }

  @Override
  public void close() throws IOException {
    channel.close();
  }

  @Override
  public void flush() throws IOException {
    buffer.flip();
    channel.write(buffer);
    buffer.clear();
  }

  @Override
  public void newLine() throws IOException {
    writeString(NEW_LINE);
  }

  @Override
  public void write(ByteSource source) throws IOException {
    try (InputStream in = source.openStreamChecked()) {
      int c;
      while ((c = in.read()) != -1) {
        int space = buffer.capacity() - buffer.position();

        if (space == 0) {
          flush();
        }

        buffer.put((byte) c);
      }
    }
  }

  @Override
  public void writeString(String text) throws IOException {
    byte[] bytes = text.getBytes();
    int index = 0;
    int remaining = bytes.length;

    while (remaining > 0) {
      int space = buffer.capacity() - buffer.position();

      if (space == 0) {
        flush();
        continue;
      }

      int count = Math.min(space, remaining);
      buffer.put(bytes, index, count);
      index += count;
      remaining -= count;
    }
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy