001/*
002 * (C) Copyright 2006-2011 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 *     bstefanescu
018 */
019package org.nuxeo.ecm.automation.client.model;
020
021import java.io.ByteArrayInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024
025/**
026 * An in memory bob containing a string.
027 *
028 * @author bstefanescu
029 */
030public class StringBlob extends Blob {
031
032    private static final long serialVersionUID = -7170366401800302228L;
033
034    /** content */
035    protected final String content;
036
037    protected String charset;
038
039    public StringBlob(String content) {
040        this.content = content;
041    }
042
043    /**
044     * Creates a <code>StringBlob</code> that is used in the Blob.Attach call
045     *
046     * @param fileName Name that is used to save the file as
047     * @param content Base64 encoded content
048     */
049    public StringBlob(String fileName, String content) {
050        super(fileName, null);
051        this.content = content;
052    }
053
054    /**
055     * Creates a <code>StringBlob</code> that is used in the Blob.Attach call
056     *
057     * @param fileName Name that is used to save the file as
058     * @param content Base64 encoded content
059     * @param mimeType Mime type to use for this content
060     */
061    public StringBlob(String fileName, String content, String mimeType) {
062        super(fileName, mimeType);
063        this.content = content;
064    }
065
066    /**
067     * Set the charset to be used when to transform the content into a byte stream. If npt specified the default charset
068     * will be used.
069     *
070     * @param charset
071     */
072    public void setCharset(String charset) {
073        this.charset = charset;
074    }
075
076    public String getCharset() {
077        return charset;
078    }
079
080    @Override
081    public InputStream getStream() throws IOException {
082        byte[] bytes = charset == null ? content.getBytes() : content.getBytes(charset);
083        return new ByteArrayInputStream(bytes);
084    }
085
086    @Override
087    public String toString() {
088        return content;
089    }
090
091    @Override
092    public int getLength() {
093        return content.length();
094    }
095}