1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jelly.tags.util;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.FileNotFoundException;
22 import java.io.InputStream;
23 import java.io.IOException;
24 import java.util.Enumeration;
25 import java.util.Properties;
26
27 import org.apache.commons.jelly.JellyTagException;
28 import org.apache.commons.jelly.TagSupport;
29 import org.apache.commons.jelly.XMLOutput;
30
31 /***
32 * A tag which loads a properties file from a given file name or URI
33 * which are loaded into the current context.
34 *
35 * @author Jim Birchfield
36 * @version $Revision: 1.6 $
37 */
38 public class PropertiesTag extends TagSupport {
39 private String file;
40 private String uri;
41 private String var;
42
43 public PropertiesTag() {
44 }
45
46
47
48 public void doTag(final XMLOutput output) throws JellyTagException {
49 if (file == null && uri == null) {
50 throw new JellyTagException("This tag must define a 'file' or 'uri' attribute");
51 }
52 InputStream is = null;
53 if (file != null) {
54 File f = new File(file);
55 if (!f.exists()) {
56 throw new JellyTagException("file: " + file + " does not exist!");
57 }
58
59 try {
60 is = new FileInputStream(f);
61 } catch (FileNotFoundException e) {
62 throw new JellyTagException(e);
63 }
64 }
65 else {
66 is = context.getResourceAsStream(uri);
67 if (is == null) {
68 throw new JellyTagException( "Could not find: " + uri );
69 }
70 }
71 Properties props = new Properties();
72
73 try {
74 props.load(is);
75 } catch (IOException e) {
76 throw new JellyTagException("properties tag could not load from file",e);
77 }
78
79 if (var != null) {
80 context.setVariable(var, props);
81 }
82 else {
83 Enumeration propsEnum = props.propertyNames();
84 while (propsEnum.hasMoreElements()) {
85 String key = (String) propsEnum.nextElement();
86 String value = props.getProperty(key);
87
88
89 context.setVariable(key, value);
90 }
91 }
92
93 }
94
95
96
97
98 /***
99 * Sets the file name to be used to load the properties file.
100 */
101 public void setFile(String file) {
102 this.file = file;
103 }
104
105 /***
106 * Sets the URI of the properties file to use. This can be a full URL or a relative URI
107 * or an absolute URI to the root context of this JellyContext.
108 */
109 public void setUri(String uri) {
110 this.uri = uri;
111 }
112
113 /***
114 * If this is defined then a Properties object containing all the
115 * properties will be created and exported, otherwise the current variable
116 * scope will be set to the value of the properties.
117 *
118 * @param var The var to set
119 */
120 public void setVar(String var) {
121 this.var = var;
122 }
123
124 }