01: /*
02: * @(#)setClassPath.java 1.1 05/05/19
03: *
04: * Copyright (c) 2005 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.util.List;
12: import java.util.ArrayList;
13: import java.util.Enumeration;
14: import java.net.URL;
15: import java.net.URLClassLoader;
16: import java.net.MalformedURLException;
17: import java.io.File;
18: import pnuts.lang.Context;
19: import pnuts.lang.PnutsFunction;
20: import pnuts.lang.PnutsException;
21:
22: public class setClassPath extends PnutsFunction {
23: public setClassPath() {
24: super ("setClassPath");
25: }
26:
27: public boolean defined(int nargs) {
28: return nargs == 1;
29: }
30:
31: static void setURLs(URL[] urls, Context context) {
32: URLClassLoader ucl = new URLClassLoader(urls, Thread
33: .currentThread().getContextClassLoader());
34: context.setClassLoader(ucl);
35: Thread.currentThread().setContextClassLoader(ucl);
36: }
37:
38: protected Object exec(Object[] args, Context context) {
39: if (args.length != 1) {
40: undefined(args, context);
41: return null;
42: }
43: Object arg = args[0];
44: if (arg == null) {
45:
46: context.setClassLoader(null);
47: Thread.currentThread().setContextClassLoader(null);
48: } else {
49: Enumeration e = context.getConfiguration().toEnumeration(
50: arg);
51: if (e != null) {
52: ArrayList list = new ArrayList();
53: try {
54: while (e.hasMoreElements()) {
55: Object elem = e.nextElement();
56: if (elem instanceof String) {
57: File file = PathHelper.getFile(
58: (String) elem, context);
59: list.add(file.toURL());
60: } else if (elem instanceof File) {
61: list.add(((File) elem).toURL());
62: } else if (elem instanceof URL) {
63: list.add(elem);
64: } else {
65: throw new IllegalArgumentException(String
66: .valueOf(elem));
67: }
68: }
69: } catch (MalformedURLException mue) {
70: throw new PnutsException(mue, context);
71: }
72: URL[] urls = new URL[list.size()];
73: list.toArray(urls);
74: setURLs(urls, context);
75: } else {
76: throw new IllegalArgumentException(String.valueOf(arg));
77: }
78: }
79: return null;
80: }
81:
82: public String toString() {
83: return "function setClassPath(urlsOrPaths)";
84: }
85: }
|