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
020import org.apache.commons.logging.Log;
021import org.apache.commons.logging.LogFactory;
022
023/**
024 * Blob based on a string.
025 */
026public class StringBlob extends AbstractBlob implements Serializable {
027
028    private static final long serialVersionUID = 1L;
029
030    private static final Log log = LogFactory.getLog(StringBlob.class);
031
032    protected final String string;
033
034    public StringBlob(String content) {
035        this(content, TEXT_PLAIN, UTF_8);
036    }
037
038    public StringBlob(String string, String mimeType) {
039        this(string, mimeType, UTF_8);
040    }
041
042    public StringBlob(String string, String mimeType, String encoding) {
043        if (string == null) {
044            throw new NullPointerException("null string");
045        }
046        this.string = string;
047        this.mimeType = mimeType;
048        this.encoding = encoding;
049    }
050
051    public StringBlob(String string, String mimeType, String encoding, String filename) {
052        this(string, mimeType, encoding);
053        setFilename(filename);
054    }
055
056    @Override
057    public long getLength() {
058        try {
059            return getByteArray().length;
060        } catch (IOException e) {
061            log.error("Error while getting byte array from blob, returning -1: " + getFilename());
062            return -1;
063        }
064    }
065
066    @Override
067    public InputStream getStream() throws IOException {
068        return new ByteArrayInputStream(getByteArray());
069    }
070
071    @Override
072    public byte[] getByteArray() throws IOException {
073        return string.getBytes(getEncoding() == null ? UTF_8 : getEncoding());
074    }
075
076    @Override
077    public String getString() {
078        return string;
079    }
080
081}