package org.asynchttpclient.providers.netty4;

import io.netty.buffer.ByteBuf;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.asynchttpclient.FluentCaseInsensitiveStringsMap;
import org.asynchttpclient.listener.TransferCompletionHandler;

class NettyTransferAdapter extends TransferCompletionHandler.TransferAdapter {

    private final ByteBuf content;
    private final FileInputStream file;
    private int byteRead = 0;

    public NettyTransferAdapter(FluentCaseInsensitiveStringsMap headers, ByteBuf content, File file) throws IOException {
        super(headers);
        this.content = content;
        if (file != null) {
            this.file = new FileInputStream(file);
        } else {
            this.file = null;
        }
    }

    @Override
    public void getBytes(byte[] bytes) {
        if (content.writableBytes() != 0) {
            content.getBytes(byteRead, bytes);
            byteRead += bytes.length;
        } else if (file != null) {
            try {
                byteRead += file.read(bytes);
            } catch (IOException e) {
                NettyAsyncHttpProvider.LOGGER.error(e.getMessage(), e);
            }
        }
    }
}
@@ -153,16 +153,66 @@
 ception;
+%0Aimport java.util.concurrent.atomic.AtomicInteger;
 %0A%0Aimport
@@ -500,24 +500,53 @@
 ate 
-int byteRead = 0
+AtomicInteger byteRead = new AtomicInteger(0)
 ;%0A%0A 
@@ -1005,42 +1005,19 @@
 Read
-, bytes);%0A            byteRead += 
+.getAndAdd(
 byte
@@ -1024,16 +1024,25 @@
 s.length
+), bytes)
 ;%0A      
@@ -1116,12 +1116,19 @@
 Read
- += 
+.getAndAdd(
 file
@@ -1135,24 +1135,25 @@
 .read(bytes)
+)
 ;%0A          

Make NettyTransferAdapter thread safe