KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > jsp > java > JspUseBean


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  * Free SoftwareFoundation, Inc.
23  * 59 Temple Place, Suite 330
24  * Boston, MA 02111-1307 USA
25  *
26  * @author Scott Ferguson
27  */

28
29 package com.caucho.jsp.java;
30
31 import com.caucho.jsp.JspParseException;
32 import com.caucho.vfs.WriteStream;
33 import com.caucho.xml.QName;
34
35 import java.io.IOException JavaDoc;
36 import java.lang.reflect.Constructor JavaDoc;
37 import java.lang.reflect.Modifier JavaDoc;
38
39 /**
40  * Represents a Java scriptlet.
41  */

42 public class JspUseBean extends JspContainerNode {
43   private static final QName ID = new QName("id");
44   private static final QName TYPE = new QName("type");
45   private static final QName CLASS = new QName("class");
46   private static final QName BEAN_NAME = new QName("beanName");
47   private static final QName SCOPE = new QName("scope");
48   
49   private String JavaDoc _id;
50   private String JavaDoc _typeName;
51   private String JavaDoc _className;
52   private String JavaDoc _beanName;
53   private String JavaDoc _scope;
54
55   /**
56    * Adds an attribute.
57    */

58   public void addAttribute(QName name, String JavaDoc value)
59     throws JspParseException
60   {
61     if (ID.equals(name))
62       _id = value;
63     else if (TYPE.equals(name))
64       _typeName = value;
65     else if (CLASS.equals(name))
66       _className = value;
67     else if (BEAN_NAME.equals(name))
68       _beanName = value;
69     else if (SCOPE.equals(name))
70       _scope = value;
71     else
72       throw error(L.l("'{0}' is an invalid attribute in <jsp:useBean>",
73                       name.getName()));
74   }
75
76   /**
77    * Adds text to the scriptlet.
78    */

79   public JspNode addText(String JavaDoc text)
80     throws JspParseException
81   {
82     JspNode node = new StaticText(_gen, text, this);
83     
84     addChild(node);
85
86     return node;
87   }
88
89   /**
90    * Generates the XML text representation for the tag validation.
91    *
92    * @param os write stream to the generated XML.
93    */

94   public void printXml(WriteStream os)
95     throws IOException JavaDoc
96   {
97     os.print("<jsp:userBean");
98
99     if (_id != null)
100       os.print(" id=\"" + _id + "\"");
101     if (_typeName != null)
102       os.print(" type=\"" + _typeName + "\"");
103     if (_className != null)
104       os.print(" class=\"" + _className + "\"");
105     if (_beanName != null)
106       os.print(" beanName=\"" + _beanName + "\"");
107     if (_scope != null)
108       os.print(" scope=\"" + _scope + "\"");
109     os.print("/>");
110   }
111
112   /**
113    * Generates the code for the scriptlet
114    *
115    * @param out the output writer for the generated java.
116    */

117   public void generate(JspJavaWriter out)
118     throws Exception JavaDoc
119   {
120     if (_id == null)
121       throw error(L.l("<jsp:useBean> expects an 'id' attribute. id specifies the variable name for the bean."));
122
123     if (_typeName == null)
124       _typeName = _className;
125     
126     if (_typeName == null)
127       throw error(L.l("<jsp:useBean> expects a 'type' or 'class' attribute. The 'type' specifies the Java type of the bean."));
128
129     // Save the bean's type
130
_gen.addBeanClass(_id, _typeName);
131
132     String JavaDoc context = null;
133     if (_scope == null || _scope.equals("page"))
134       context = "pageContext";
135     else if (_scope.equals("request")) {
136       context = "pageContext.getRequest()";
137     }
138     else if (_scope.equals("session")) {
139       context = "pageContext.getSession()";
140     }
141     else if (_scope.equals("application")) {
142       context = "pageContext.getApplication()";
143     }
144     else
145       throw error(L.l("Unknown scope '{0}' in <jsp:useBean>. Scope must be 'page', 'request', 'session', or 'application'.", _scope));
146
147     // declare the bean
148
out.println(_typeName + " " + _id + ";");
149
150     // application and session beans need synchronization
151
if ("application".equals(_scope) || "session".equals(_scope)) {
152       out.println("synchronized (" + context + ") {");
153       out.pushDepth();
154     }
155
156     // try to get the bean from the context
157
out.print(_id + " = (" + _typeName + ") " + context);
158     out.println(".getAttribute(\"" + _id + "\");");
159
160     // If the bean is new, then instantiate it
161
out.println("if (" + _id + " == null) {");
162     out.pushDepth();
163
164     boolean canInstantiate = false;
165
166     // instantiate a class
167
if (_className != null) {
168       String JavaDoc msg = canInstantiateBean(_className);
169       if (msg == null) {
170     out.println(_id + " = new " + _className + "();");
171     canInstantiate = true;
172       }
173       else
174     out.println("throw new java.lang.InstantiationException(\"" + msg + "\");");
175     }
176     else if (_beanName == null)
177       out.println("throw new java.lang.InstantiationException(\"jsp:useBean needs 'bean' or 'class'\");");
178     // instantiate beans with a request time attribute
179
else if (hasRuntimeAttribute(_beanName)) {
180       String JavaDoc beanName = getRuntimeAttribute(_beanName);
181       out.println(_id + " = (" + _typeName +
182           ") java.beans.Beans.instantiate(getClass().getClassLoader(), " +
183           beanName + ");");
184       canInstantiate = true;
185     }
186     // instantiate a beans
187
else {
188       out.println(_id + " = (" + _typeName +
189           ") java.beans.Beans.instantiate(getClass().getClassLoader(), \"" +
190           _beanName + "\");");
191       canInstantiate = true;
192     }
193
194     // Save it in the context
195
if (! canInstantiate) {
196     }
197     else
198       out.println(context + ".setAttribute(\"" + _id + "\", " + _id + ");");
199
200     // Initialize the new bean
201
if (canInstantiate)
202       generateChildren(out);
203
204     out.popDepth();
205     out.println("}");
206
207     // Close the synchronization if necessary
208
if ("application".equals(_scope) || "session".equals(_scope)) {
209       out.popDepth();
210       out.println("}");
211     }
212   }
213
214   /**
215    * Tests if the bean can be instantiated.
216    */

217   private String JavaDoc canInstantiateBean(String JavaDoc className)
218     throws Exception JavaDoc
219   {
220     try {
221       Class JavaDoc cl = _gen.getBeanClass(className);
222       int modifiers = cl.getModifiers();
223       if (Modifier.isInterface(modifiers))
224     return L.l("'{0}' is an interface", className);
225       if (Modifier.isAbstract(modifiers))
226     return L.l("'{0}' is abstract", className);
227       if (! Modifier.isPublic(modifiers))
228     return L.l("'{0}' must be public", className);
229
230       Constructor JavaDoc []constructors = cl.getConstructors();
231       for (int i = 0; i < constructors.length; i++) {
232
233     Class JavaDoc []param = constructors[i].getParameterTypes();
234     if (param.length == 0)
235       return null;
236       }
237     } catch (Exception JavaDoc e) {
238       throw error(e.getMessage());
239     }
240
241     return L.l("'{0}' has no public zero-arg constructor", className);
242   }
243 }
244
Popular Tags