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