001 /** 002 * 003 * Copyright 2003-2004 The Apache Software Foundation 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018 package javax.activation; 019 020 import java.io.IOException; 021 import java.io.InputStream; 022 import java.io.OutputStream; 023 import java.net.URL; 024 import java.net.URLConnection; 025 026 /** 027 * @version $Rev: 123385 $ $Date: 2004-12-26 19:54:49 -0800 (Sun, 26 Dec 2004) $ 028 */ 029 public class URLDataSource implements DataSource { 030 private final static String DEFAULT_CONTENT_TYPE = "application/octet-stream"; 031 032 private final URL url; 033 034 /** 035 * Creates a URLDataSource from a URL object. 036 */ 037 public URLDataSource(URL url) { 038 this.url = url; 039 } 040 041 /** 042 * Returns the value of the URL content-type header field. 043 * This method calls URL.openConnection() to obtain a connection 044 * from which to obtain the content type. If this fails or 045 * a getContentType() returns null then "application/octet-stream" 046 * is returned. 047 */ 048 public String getContentType() { 049 try { 050 URLConnection connection = url.openConnection(); 051 String type = connection.getContentType(); 052 return type == null ? DEFAULT_CONTENT_TYPE : type; 053 } catch (IOException e) { 054 return DEFAULT_CONTENT_TYPE; 055 } 056 } 057 058 /** 059 * Returns the file name of the URL object. 060 * @return the name as returned by URL.getFile() 061 */ 062 public String getName() { 063 return url.getFile(); 064 } 065 066 /** 067 * Returns an InputStream obtained from the URL. 068 * @return the InputStream from URL.openStream() 069 */ 070 public InputStream getInputStream() throws IOException { 071 return url.openStream(); 072 } 073 074 /** 075 * Returns an OutputStream obtained from the URL. 076 */ 077 public OutputStream getOutputStream() throws IOException { 078 URLConnection connection = url.openConnection(); 079 connection.setDoOutput(true); 080 return connection.getOutputStream(); 081 } 082 083 /** 084 * Returns the URL of the data source. 085 */ 086 public URL getURL() { 087 return url; 088 } 089 }