001 package railo.runtime.net.smtp; 002 003 import java.io.ByteArrayInputStream; 004 import java.io.IOException; 005 import java.io.InputStream; 006 import java.io.OutputStream; 007 import java.net.URL; 008 import java.net.URLConnection; 009 010 import javax.activation.DataSource; 011 012 import railo.commons.io.IOUtil; 013 014 public final class URLDataSource2 implements DataSource { 015 016 private URL url; 017 private final static String DEFAULT_CONTENT_TYPE = "application/octet-stream"; 018 private byte[] barr; 019 020 /** 021 * Creates a URLDataSource from a URL object 022 */ 023 public URLDataSource2(URL url) { 024 this.url = url; 025 } 026 027 /** 028 * Returns the value of the URL content-type header field 029 * 030 */ 031 public String getContentType() { 032 URLConnection connection = null; 033 try { 034 connection = url.openConnection(); 035 } catch (IOException e) { 036 } 037 if (connection == null) 038 return DEFAULT_CONTENT_TYPE; 039 040 return connection.getContentType(); 041 042 } 043 044 /** 045 * Returns the file name of the URL object 046 */ 047 public String getName() { 048 return url.getFile(); 049 } 050 051 /** 052 * Returns an InputStream obtained from the data source 053 */ 054 public InputStream getInputStream() throws IOException { 055 if(barr==null) { 056 barr=IOUtil.toBytes(url.openStream()); 057 } 058 return new ByteArrayInputStream(barr); 059 } 060 061 /** 062 * Returns an OutputStream obtained from the data source 063 */ 064 public OutputStream getOutputStream() throws IOException { 065 066 URLConnection connection = url.openConnection(); 067 if (connection == null) 068 return null; 069 070 connection.setDoOutput(true); //is it necessary? 071 return connection.getOutputStream(); 072 } 073 074 /** 075 * Returns the URL of the data source 076 */ 077 public URL getURL() { 078 return url; 079 } 080 }