01: /* JFox, the OpenSource J2EE Application Server
02: *
03: * Copyright (C) 2002 huihoo.com
04: * Distributable under GNU LGPL license
05: * See the GNU Lesser General Public License for more details.
06: */
07:
08: package org.huihoo.jfox.jndi.url;
09:
10: import java.net.URL;
11: import java.net.URLStreamHandler;
12: import java.net.URLConnection;
13: import java.net.URLStreamHandlerFactory;
14: import java.net.MalformedURLException;
15: import java.io.IOException;
16:
17: import org.huihoo.jfox.jndi.JNDIProperties;
18: import javax.naming.Context;
19: import javax.naming.NamingException;
20:
21: /**
22: *
23: * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
24: */
25:
26: public class JndiURL {
27:
28: static {
29: URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
30: public URLStreamHandler createURLStreamHandler(
31: String protocol) {
32: return new URLStreamHandler() {
33: protected URLConnection openConnection(URL u)
34: throws IOException {
35: throw new UnsupportedOperationException(
36: "openConnection");
37: }
38: };
39: }
40: });
41: }
42:
43: public static URL getURL(Context ctx, String url)
44: throws MalformedURLException {
45: url = url.trim();
46: if (url.endsWith("/")) { // 去掉最后的 /
47: url = url.substring(0, url.length() - 1);
48: }
49:
50: if (url.indexOf(':') > 0) { // 完整的绝对路径 java://host:port
51: URL temp = new URL(url);
52: if (temp.getPort() == -1) { // 没有设置 Port
53: return new URL(temp.getProtocol(), temp.getHost(),
54: JNDIProperties.DEFAULT_PORT, temp.getPath());
55: }
56: } else {
57: if (url.startsWith("/")) {
58: return new URL(JNDIProperties.DEFAULT_SCHEME,
59: JNDIProperties.DEFAULT_HOST,
60: JNDIProperties.DEFAULT_PORT, url);
61: } else {
62: try {
63: String nameSpace = ctx.getNameInNamespace();
64:
65: String absUrl = nameSpace.endsWith("/") ? nameSpace
66: + url : nameSpace + "/" + url;
67: return new URL(JNDIProperties.DEFAULT_SCHEME,
68: JNDIProperties.DEFAULT_HOST,
69: JNDIProperties.DEFAULT_PORT, absUrl);
70:
71: } catch (NamingException e) {
72:
73: }
74: }
75: }
76: return new URL(url);
77: }
78:
79: public static void main(String[] args) {
80:
81: }
82:
83: }
|