001/*
002 * Copyright (c) 2006-2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Bogdan Stefanescu
011 *     Florent Guillaume
012 */
013package org.nuxeo.ecm.core.api.impl.blob;
014
015import java.io.ByteArrayInputStream;
016import java.io.IOException;
017import java.io.InputStream;
018import java.io.Serializable;
019
020/**
021 * Blob based on a byte array.
022 */
023public class ByteArrayBlob extends AbstractBlob implements Serializable {
024
025    private static final long serialVersionUID = 1L;
026
027    protected final byte[] bytes;
028
029    public ByteArrayBlob(byte[] bytes) {
030        this(bytes, null, null);
031    }
032
033    public ByteArrayBlob(byte[] bytes, String mimeType) {
034        this(bytes, mimeType, null);
035    }
036
037    public ByteArrayBlob(byte[] bytes, String mimeType, String encoding) {
038        if (bytes == null) {
039            throw new NullPointerException("null bytes");
040        }
041        this.bytes = bytes;
042        this.mimeType = mimeType;
043        this.encoding = encoding;
044    }
045
046    @Override
047    public long getLength() {
048        return bytes.length;
049    }
050
051    @Override
052    public InputStream getStream() {
053        return new ByteArrayInputStream(bytes);
054    }
055
056    @Override
057    public byte[] getByteArray() {
058        return bytes;
059    }
060
061    @Override
062    public String getString() throws IOException {
063        return new String(bytes, getEncoding() == null ? UTF_8 : getEncoding());
064    }
065
066}