01: /*
02: * @(#)loadProperties.java 1.2 04/12/06
03: *
04: * Copyright (c) 2001-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.util;
10:
11: import pnuts.lang.Pnuts;
12: import pnuts.lang.PnutsException;
13: import pnuts.lang.PnutsFunction;
14: import pnuts.lang.Context;
15: import java.net.URL;
16: import java.util.Properties;
17: import java.io.InputStream;
18: import java.io.File;
19: import java.io.FileInputStream;
20: import java.io.IOException;
21: import java.io.FileNotFoundException;
22:
23: /*
24: * function loadProperties(input)
25: */
26: public class loadProperties extends PnutsFunction {
27:
28: public loadProperties() {
29: super ("loadProperties");
30: }
31:
32: public boolean defined(int nargs) {
33: return nargs == 1 || nargs == 2;
34: }
35:
36: protected Object exec(Object[] args, Context context) {
37: int nargs = args.length;
38: Properties prop;
39: if (nargs == 1) {
40: prop = new Properties();
41: } else if (nargs == 2) {
42: prop = (Properties) args[1];
43: } else {
44: undefined(args, context);
45: return null;
46: }
47: Object arg0 = args[0];
48: InputStream in = null;
49: try {
50: if (arg0 instanceof String) {
51: URL url = Pnuts.getResource((String) args[0], context);
52: if (url == null) {
53: throw new FileNotFoundException((String) args[0]);
54: }
55: in = url.openStream();
56: try {
57: prop.load(in);
58: } finally {
59: in.close();
60: }
61: } else if (arg0 instanceof File) {
62: in = new FileInputStream((File) arg0);
63: try {
64: prop.load(in);
65: } finally {
66: in.close();
67: }
68: } else if (arg0 instanceof InputStream) {
69: prop.load((InputStream) arg0);
70: } else if (arg0 instanceof URL) {
71: in = ((URL) arg0).openStream();
72: try {
73: prop.load(in);
74: } finally {
75: in.close();
76: }
77: } else {
78: throw new IllegalArgumentException(String.valueOf(arg0));
79: }
80: return prop;
81: } catch (IOException e) {
82: throw new PnutsException(e, context);
83: }
84: }
85:
86: public String toString() {
87: return "function loadProperties(String|File|InputStream|URL)";
88: }
89: }
|