001/*
002 * (C) Copyright 2006-2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Bogdan Stefanescu
018 *     Florent Guillaume
019 */
020package org.nuxeo.ecm.core.api.impl.blob;
021
022import java.io.ByteArrayInputStream;
023import java.io.IOException;
024import java.io.InputStream;
025import java.io.Serializable;
026
027import org.apache.commons.logging.Log;
028import org.apache.commons.logging.LogFactory;
029
030/**
031 * Blob based on a string.
032 */
033public class StringBlob extends AbstractBlob implements Serializable {
034
035    private static final long serialVersionUID = 1L;
036
037    private static final Log log = LogFactory.getLog(StringBlob.class);
038
039    protected final String string;
040
041    public StringBlob(String content) {
042        this(content, TEXT_PLAIN, UTF_8);
043    }
044
045    public StringBlob(String string, String mimeType) {
046        this(string, mimeType, UTF_8);
047    }
048
049    public StringBlob(String string, String mimeType, String encoding) {
050        if (string == null) {
051            throw new NullPointerException("null string");
052        }
053        this.string = string;
054        this.mimeType = mimeType;
055        this.encoding = encoding;
056    }
057
058    public StringBlob(String string, String mimeType, String encoding, String filename) {
059        this(string, mimeType, encoding);
060        setFilename(filename);
061    }
062
063    @Override
064    public long getLength() {
065        try {
066            return getByteArray().length;
067        } catch (IOException e) {
068            log.error("Error while getting byte array from blob, returning -1: " + getFilename());
069            return -1;
070        }
071    }
072
073    @Override
074    public InputStream getStream() throws IOException {
075        return new ByteArrayInputStream(getByteArray());
076    }
077
078    @Override
079    public byte[] getByteArray() throws IOException {
080        return string.getBytes(getEncoding() == null ? UTF_8 : getEncoding());
081    }
082
083    @Override
084    public String getString() {
085        return string;
086    }
087
088}