aboutsummaryrefslogtreecommitdiffstats
path: root/jdisc_core/src/main/java/com/yahoo/jdisc/handler/AbstractContentOutputStream.java
blob: 972d0c0b9b4688e538d68f95ff703e42bdc7a774 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;

import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Objects;

/**
 * @author Simon Thoresen Hult
 */
abstract class AbstractContentOutputStream extends OutputStream {

    public static final int BUFFERSIZE = 4096;
    private ByteBuffer current;

    @Override
    public final void write(int b) {
        if (current == null) {
            current = ByteBuffer.allocate(BUFFERSIZE);
        }
        current.put((byte)b);
        if (current.remaining() == 0) {
            flush();
        }
    }

    @Override
    public final void write(byte[] buffer, int offset, int length) {
        Objects.requireNonNull(buffer, "buf");
        if (current == null) {
            current = ByteBuffer.allocate(BUFFERSIZE + length);
        }
        int part = Math.min(length, current.remaining());
        current.put(buffer, offset, part);
        if (current.remaining() == 0) {
            flush();
        }
        if (part < length) {
            write(buffer, offset + part, length - part);
        }
    }

    @Override
    public final void write(byte[] buffer) {
        write(buffer, 0, buffer.length);
    }

    @Override
    public final void flush() {
        if (current == null || current.position() == 0) {
            return;
        }
        ByteBuffer buf = current;
        current = null;
        buf.flip();
        doFlush(buf);
    }

    @Override
    public final void close() {
        flush();
        doClose();
    }

    protected abstract void doFlush(ByteBuffer buf);

    protected abstract void doClose();

}