BlobOutputStream.java 2.16 KB
/*
 * Decompiled with CFR 0_118.
 */
package com.day.crx.delite.impl.support;

import com.day.crx.delite.impl.support.Blob;
import com.day.crx.delite.impl.support.BlobFactoryImpl;
import com.day.crx.delite.impl.support.BlobImpl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class BlobOutputStream
extends OutputStream {
    private int treshhold = 65536;
    private byte[] data = null;
    private int length = 0;
    private File file;
    private OutputStream out = new ByteArrayOutputStream();
    private final BlobFactoryImpl factory;

    public BlobOutputStream(BlobFactoryImpl factory) {
        this.factory = factory;
    }

    public void write(byte[] bytes, int off, int len) throws IOException {
        if (this.out == null) {
            throw new IllegalStateException("Stream already closed.");
        }
        if (this.file == null && len + this.length > this.treshhold) {
            this.close();
            this.file = this.factory.allocateTmpFile();
            this.out = new FileOutputStream(this.file);
            this.out.write(this.data);
            this.data = null;
        }
        this.out.write(bytes, off, len);
        this.length += len;
    }

    public void write(byte[] b) throws IOException {
        this.write(b, 0, b.length);
    }

    public void close() throws IOException {
        if (this.out instanceof ByteArrayOutputStream) {
            ByteArrayOutputStream bof = (ByteArrayOutputStream)this.out;
            bof.close();
            this.data = bof.toByteArray();
            this.file = null;
            this.out = null;
        } else if (this.out instanceof FileOutputStream) {
            this.out.close();
            this.data = null;
            this.out = null;
        }
    }

    public Blob getBlob() throws IOException {
        this.close();
        BlobImpl blob = this.file == null ? new BlobImpl(this.factory, this.data) : new BlobImpl(this.factory, this.file);
        return this.factory.register(blob);
    }

    public void write(int b) throws IOException {
        this.write(new byte[]{(byte)b}, 0, 1);
    }
}