001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.net.smtp;
020
021import java.io.ByteArrayInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.net.URL;
026import java.net.URLConnection;
027
028import javax.activation.DataSource;
029
030import lucee.commons.io.IOUtil;
031
032public final class URLDataSource2 implements DataSource {
033
034    private URL url;
035    private final static String DEFAULT_CONTENT_TYPE = "application/octet-stream";
036    private byte[] barr;
037
038    /**
039     * Creates a URLDataSource from a URL object
040     */
041    public URLDataSource2(URL url) {
042        this.url = url;
043    }
044
045    /**
046     * Returns the value of the URL content-type header field
047     * 
048     */
049    public String getContentType() {
050        URLConnection connection = null;
051        try {
052            connection = url.openConnection();
053        } catch (IOException e) {
054        }
055        if (connection == null)
056            return DEFAULT_CONTENT_TYPE;
057
058        return connection.getContentType();
059
060    }
061
062    /**
063     * Returns the file name of the URL object
064     */
065    public String getName() {
066        return url.getFile();
067    }
068
069    /**
070     * Returns an InputStream obtained from the data source
071     */
072    public InputStream getInputStream() throws IOException {
073        if(barr==null) {
074                barr=IOUtil.toBytes(url.openStream());
075        }
076        return new ByteArrayInputStream(barr);
077    }
078
079    /**
080     * Returns an OutputStream obtained from the data source
081     */
082    public OutputStream getOutputStream() throws IOException {
083
084        URLConnection connection = url.openConnection();
085        if (connection == null)
086            return null;
087
088        connection.setDoOutput(true); //is it necessary?
089        return connection.getOutputStream();
090    }
091
092    /**
093     * Returns the URL of the data source
094     */
095    public URL getURL() {
096        return url;
097    }
098}