1 /**
2 *
3 * Copyright 2003-2004 The Apache Software Foundation
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package javax.activation;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.net.URL;
24 import java.net.URLConnection;
25
26 /**
27 * @version $Rev: 123385 $ $Date: 2004-12-26 19:54:49 -0800 (Sun, 26 Dec 2004) $
28 */
29 public class URLDataSource implements DataSource {
30 private final static String DEFAULT_CONTENT_TYPE = "application/octet-stream";
31
32 private final URL url;
33
34 /**
35 * Creates a URLDataSource from a URL object.
36 */
37 public URLDataSource(URL url) {
38 this.url = url;
39 }
40
41 /**
42 * Returns the value of the URL content-type header field.
43 * This method calls URL.openConnection() to obtain a connection
44 * from which to obtain the content type. If this fails or
45 * a getContentType() returns null then "application/octet-stream"
46 * is returned.
47 */
48 public String getContentType() {
49 try {
50 URLConnection connection = url.openConnection();
51 String type = connection.getContentType();
52 return type == null ? DEFAULT_CONTENT_TYPE : type;
53 } catch (IOException e) {
54 return DEFAULT_CONTENT_TYPE;
55 }
56 }
57
58 /**
59 * Returns the file name of the URL object.
60 * @return the name as returned by URL.getFile()
61 */
62 public String getName() {
63 return url.getFile();
64 }
65
66 /**
67 * Returns an InputStream obtained from the URL.
68 * @return the InputStream from URL.openStream()
69 */
70 public InputStream getInputStream() throws IOException {
71 return url.openStream();
72 }
73
74 /**
75 * Returns an OutputStream obtained from the URL.
76 */
77 public OutputStream getOutputStream() throws IOException {
78 URLConnection connection = url.openConnection();
79 connection.setDoOutput(true);
80 return connection.getOutputStream();
81 }
82
83 /**
84 * Returns the URL of the data source.
85 */
86 public URL getURL() {
87 return url;
88 }
89 }