BlobImpl.java 2.64 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 java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BlobImpl
implements Blob {
    private byte[] data = null;
    private File tmpFile;
    private final BlobFactoryImpl factory;
    private boolean detached;

    BlobImpl(BlobFactoryImpl factory, byte[] bytes) {
        this.factory = factory;
        this.data = bytes;
    }

    BlobImpl(BlobFactoryImpl factory, File file) {
        this.factory = factory;
        this.tmpFile = file;
    }

    public byte[] getBytes() throws IOException {
        if (this.data == null) {
            this.data = new byte[(int)this.tmpFile.length()];
            FileInputStream in = new FileInputStream(this.tmpFile);
            in.read(this.data);
            in.close();
        }
        return this.data;
    }

    public byte[] getBytes(int off, int len) throws IOException {
        if ((long)(off + len) > this.size()) {
            throw new IndexOutOfBoundsException("" + (off + len));
        }
        if (off == 0 && (long)len == this.size()) {
            return this.getBytes();
        }
        if (this.data != null) {
            byte[] ret = new byte[len];
            System.arraycopy(this.data, off, ret, 0, len);
            return ret;
        }
        FileInputStream in = new FileInputStream(this.tmpFile);
        byte[] ret = new byte[len];
        in.skip(off);
        in.read(ret);
        in.close();
        return ret;
    }

    public long size() throws IOException {
        return this.tmpFile == null ? (long)this.data.length : this.tmpFile.length();
    }

    void discard() throws IOException {
        this.data = null;
        if (this.tmpFile != null && !this.detached) {
            this.factory.freeTmpFile(this.tmpFile);
        }
    }

    public void close() throws IOException {
        this.factory.discard(this);
    }

    public InputStream getInputStream() throws IOException {
        return this.tmpFile == null ? new ByteArrayInputStream(this.data) : new FileInputStream(this.tmpFile);
    }

    public File getFile() throws IOException {
        if (this.tmpFile == null) {
            this.tmpFile = this.factory.allocateTmpFile();
            FileOutputStream out = new FileOutputStream(this.tmpFile);
            out.write(this.data);
            out.close();
        }
        return this.tmpFile;
    }

    public void detach() {
        this.detached = true;
    }
}