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: 155420 $
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 finally {
79 if (is != null) {
80 try {
81 is.close();
82 } catch (IOException ioe) {
83 ;
84 }
85 }
86 }
87
88 if (var != null) {
89 context.setVariable(var, props);
90 }
91 else {
92 Enumeration propsEnum = props.propertyNames();
93 while (propsEnum.hasMoreElements()) {
94 String key = (String) propsEnum.nextElement();
95 String value = props.getProperty(key);
96
97
98 context.setVariable(key, value);
99 }
100 }
101
102 }
103
104
105
106
107 /***
108 * Sets the file name to be used to load the properties file.
109 */
110 public void setFile(String file) {
111 this.file = file;
112 }
113
114 /***
115 * Sets the URI of the properties file to use. This can be a full URL or a relative URI
116 * or an absolute URI to the root context of this JellyContext.
117 */
118 public void setUri(String uri) {
119 this.uri = uri;
120 }
121
122 /***
123 * If this is defined then a Properties object containing all the
124 * properties will be created and exported, otherwise the current variable
125 * scope will be set to the value of the properties.
126 *
127 * @param var The var to set
128 */
129 public void setVar(String var) {
130 this.var = var;
131 }
132
133 }