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