001package ball.activation;
002/*-
003 * ##########################################################################
004 * Utilities
005 * $Id: ByteArrayDataSource.java 5856 2020-04-27 20:21:05Z ball $
006 * $HeadURL: svn+ssh://svn.hcf.dev/var/spool/scm/repository.svn/ball-util/trunk/src/main/java/ball/activation/ByteArrayDataSource.java $
007 * %%
008 * Copyright (C) 2008 - 2020 Allen D. Ball
009 * %%
010 * Licensed under the Apache License, Version 2.0 (the "License");
011 * you may not use this file except in compliance with the License.
012 * You may obtain a copy of the License at
013 *
014 *      http://www.apache.org/licenses/LICENSE-2.0
015 *
016 * Unless required by applicable law or agreed to in writing, software
017 * distributed under the License is distributed on an "AS IS" BASIS,
018 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019 * See the License for the specific language governing permissions and
020 * limitations under the License.
021 * ##########################################################################
022 */
023import java.beans.ConstructorProperties;
024import java.io.ByteArrayInputStream;
025import java.io.ByteArrayOutputStream;
026import java.io.IOException;
027import java.io.InputStream;
028import java.io.OutputStream;
029import lombok.ToString;
030
031/**
032 * {@link javax.activation.DataSource} implementation based on
033 * {@link ByteArrayInputStream} and {@link ByteArrayOutputStream}.
034 *
035 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
036 * @version $Revision: 5856 $
037 */
038@ToString
039public class ByteArrayDataSource extends AbstractDataSource {
040    private final ByteArrayOutputStreamImpl out =
041        new ByteArrayOutputStreamImpl();
042
043    /**
044     * @param   name            Initial {@code "Name"} attribute value.
045     * @param   type            Initial {@code "ContentType"} attribute
046     *                          value.
047     */
048    @ConstructorProperties({ "name", "contentType" })
049    public ByteArrayDataSource(String name, String type) {
050        super();
051
052        setName(name);
053
054        if (type != null) {
055            setContentType(type);
056        }
057    }
058
059    @Override
060    public void clear() { out.reset(); }
061
062    @Override
063    public long length() { return out.size(); }
064
065    @Override
066    public InputStream getInputStream() throws IOException {
067        return out.getInputStream();
068    }
069
070    @Override
071    public OutputStream getOutputStream() throws IOException {
072        out.reset();
073
074        return out;
075    }
076
077    private class ByteArrayOutputStreamImpl extends ByteArrayOutputStream {
078        public ByteArrayOutputStreamImpl() { super(8 * 1024); }
079
080        public ByteArrayInputStream getInputStream() {
081            return new ByteArrayInputStream(buf, 0, count);
082        }
083    }
084}