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.lib;
10:
11: import java.io.File;
12: import java.io.IOException;
13: import java.net.URL;
14: import java.net.URI;
15: import java.net.MalformedURLException;
16: import pnuts.lang.Runtime;
17: import pnuts.lang.*;
18:
19: public class getURL extends PnutsFunction {
20:
21: public getURL() {
22: super ("getURL");
23: }
24:
25: public boolean defined(int nargs) {
26: return nargs == 1 || nargs == 2;
27: }
28:
29: protected Object exec(Object[] args, Context context) {
30: int nargs = args.length;
31: URL base = null;
32: if (nargs == 2) {
33: Object arg0 = args[0];
34: if (arg0 instanceof URL) {
35: base = (URL) arg0;
36: } else {
37: base = (URL) exec(new Object[] { arg0 }, context);
38: }
39: try {
40: return new URL(base, (String) args[1]);
41: } catch (MalformedURLException e) {
42: throw new PnutsException(e, context);
43: }
44: } else if (nargs == 1) {
45: Object arg = args[0];
46: if (arg instanceof URL) {
47: return (URL) arg;
48: } else if (arg instanceof File) {
49: try {
50: return Runtime.fileToURL((File) arg);
51: } catch (IOException e) {
52: throw new PnutsException(e, context);
53: }
54: } else if (arg instanceof String) {
55: try {
56: return new URL((String) arg);
57: } catch (MalformedURLException e) {
58: throw new PnutsException(e, context);
59: }
60: } else if (arg instanceof URI) {
61: try {
62: return ((URI) arg).toURL();
63: } catch (MalformedURLException e) {
64: throw new PnutsException(e, context);
65: }
66: } else {
67: throw new IllegalArgumentException(String.valueOf(arg));
68: }
69: } else {
70: undefined(args, context);
71: return null;
72: }
73: }
74:
75: public String toString() {
76: return "function getURL({base ,} url)";
77: }
78: }
|