01: /*
02: * @(#)getURL.java 1.2 04/12/06
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.servlet;
10:
11: import pnuts.servlet.*;
12: import pnuts.lang.*;
13: import java.io.*;
14: import java.net.*;
15: import javax.servlet.*;
16: import javax.servlet.http.*;
17:
18: /*
19: * getURL( { { base, } url } )
20: */
21: public class getURL extends PnutsFunction {
22:
23: public getURL() {
24: super ("getURL");
25: }
26:
27: public boolean defined(int nargs) {
28: return (nargs == 0 || nargs == 1 || nargs == 2);
29: }
30:
31: protected Object exec(Object[] args, Context context) {
32: int nargs = args.length;
33:
34: if (nargs == 2) {
35: Object arg = args[0];
36: URL base;
37: if (arg instanceof URL) {
38: base = (URL) arg;
39: } else {
40: base = (URL) exec(new Object[] { arg }, context);
41: }
42: try {
43: return new URL(base, (String) args[1]);
44: } catch (MalformedURLException e) {
45: throw new PnutsException(e, context);
46: }
47: } else if (nargs == 1) {
48: Object arg = args[0];
49: if (arg instanceof URL) {
50: return arg;
51: } else if (arg instanceof File) {
52: try {
53: return ((File) arg).toURL();
54: } catch (MalformedURLException e) {
55: throw new PnutsException(e, context);
56: }
57: } else if (arg instanceof String) {
58: try {
59: return new URL((String) arg);
60: } catch (MalformedURLException e1) {
61: String file = (String) arg;
62: HttpServletRequest request = (HttpServletRequest) context
63: .get(PnutsServlet.SERVLET_REQUEST);
64: String uri = request.getRequestURI();
65: int idx = uri.lastIndexOf('/');
66: if (idx > 0) {
67: uri = uri.substring(0, idx + 1);
68: } else {
69: uri = "/";
70: }
71: try {
72: URL base = new URL(request.getScheme() + "://"
73: + request.getServerName() + ":"
74: + request.getServerPort() + uri);
75: return new URL(base, file);
76: } catch (MalformedURLException e2) {
77: throw new PnutsException(e2, context);
78: }
79: }
80: } else {
81: throw new IllegalArgumentException();
82: }
83: } else if (nargs == 0) {
84: try {
85: HttpServletRequest request = (HttpServletRequest) context
86: .get(PnutsServlet.SERVLET_REQUEST);
87: String uri = request.getRequestURI();
88: return new URL(request.getScheme() + "://"
89: + request.getServerName() + ":"
90: + request.getServerPort() + uri);
91: } catch (MalformedURLException e) {
92: throw new PnutsException(e, context);
93: }
94: } else {
95: undefined(args, context);
96: return null;
97: }
98: }
99: }
|