KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > util > SessionTool


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2001 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "The Jakarta Project", "Commons", and "Apache Software
27  * Foundation" must not be used to endorse or promote products derived
28  * from this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation. For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  */

55 /**
56  * Provides utilities for instantiating classes out of templates.
57  *
58  * Company: Deutsches Zentrum fuer Luft- und Raumfahrt
59  * @author Christoph.Reck@dlr.de
60  *
61  * Elimintated some unused methods - Matt Avery, mavery@einnovation.com
62  */

63 package com.openedit.util;
64
65 import java.lang.reflect.Constructor JavaDoc;
66 import java.lang.reflect.Modifier JavaDoc;
67
68 import com.openedit.ModuleManager;
69 import com.openedit.WebPageRequest;
70
71 /**
72  * @author Matthew Avery, mavery@einnovation.com
73  *
74  * This class was derived from a class I found on the Velocity
75  * mailing list (see notes above) and adds some convenience methods for
76  * use with Open Edit specific implementation. It is still referenced
77  * from Velocity pages as "$classtool".
78  *
79  * December 4, 2004 - Check the Spring PluginManager first when constructing objects.
80  */

81 public class SessionTool
82 {
83     protected WebPageRequest fieldContext;
84     protected ModuleManager fieldModuleManager;
85     
86     public SessionTool( WebPageRequest inContext, ModuleManager inManager)
87     {
88         fieldContext = inContext;
89         fieldModuleManager = inManager;
90     }
91     
92     public Object JavaDoc sessionInstance( String JavaDoc inSessionKey, String JavaDoc inClassName ) throws Exception JavaDoc
93     {
94         Object JavaDoc instance = getContext().getSessionValue( inSessionKey );
95         if ( instance == null )
96         {
97             instance = construct( inSessionKey, inClassName );
98             getContext().putSessionValue( inSessionKey, instance );
99         }
100         return instance;
101     }
102
103     protected WebPageRequest getContext()
104     {
105         return fieldContext;
106     }
107     
108     public Object JavaDoc construct( String JavaDoc inKey, String JavaDoc inClassName ) throws Exception JavaDoc
109     {
110         if ( getModuleManager().containsModule( inKey ) )
111         {
112             return getModuleManager().getBean( inKey );
113         }
114         Class JavaDoc newClass = Class.forName( inClassName );
115         Constructor JavaDoc[] constructors = newClass.getConstructors();
116         for ( int i = 0; i < constructors.length; i++ )
117         {
118             Class JavaDoc[] argumentClasses = constructors[i].getParameterTypes();
119             if ( argumentClasses.length == 0 )
120             {
121                 return constructors[i].newInstance( null );
122             }
123             if ( argumentClasses.length == 1
124               && argumentClasses[0].equals( WebPageRequest.class ) )
125             {
126                 return constructors[i].newInstance( new Object JavaDoc[] { getContext() } );
127             }
128         }
129         return newClass.newInstance();
130     }
131     
132     /**
133      * Instantiates a class by specifying its name (via empty constructor).
134      *
135      * @param className The name of the class to instantiates.
136      * @return A new instance of the requested class.
137      */

138     public static Object JavaDoc newInstance(String JavaDoc className) throws Exception JavaDoc
139     {
140         Class JavaDoc cls = Class.forName(className);
141         Class JavaDoc[] params = new Class JavaDoc[0];
142
143         try
144         {
145             Constructor JavaDoc constructor = cls.getConstructor(params);
146             return constructor.newInstance( new Object JavaDoc[0] );
147         }
148         catch (Exception JavaDoc ex)
149         {
150             Constructor JavaDoc constructor = cls.getDeclaredConstructor(params);
151             if ( Modifier.isPrivate( constructor.getModifiers() ) )
152                 return cls; // class with static methods
153
}
154         return null;
155     }
156
157     /**
158      * Convenience method which instantiates a class by specifying
159      * its name and one parameter.
160      *
161      * @param className The name of the class to instantiates.
162      * @param param A single parameters used to call the constructor.
163      * @return A new instance of the requested class.
164      */

165     public static Object JavaDoc newInstance(String JavaDoc className, Object JavaDoc param)
166            throws Exception JavaDoc
167     {
168         return newInstance( className, new Object JavaDoc[] {param} );
169     }
170
171     /**
172      * Instantiates a class by specifying its name and parameters.
173      *
174      * @param className The name of the class to instantiates.
175      * @param params Array of parameters used to call the constructor.
176      * @return A new instance of the requested class.
177      */

178     public static Object JavaDoc newInstance(String JavaDoc className, Object JavaDoc[] params)
179            throws Exception JavaDoc
180     {
181         Class JavaDoc cls = Class.forName(className);
182         Constructor JavaDoc constructor = getConstructor(cls, params);
183         return constructor.newInstance(params);
184     }
185
186     /**
187      * Enhancement of the class objects own getConstructor() which takes
188      * in consideration subclassing and primitives. The params
189      * parameter is an array of objects that should be matched
190      * classwise to the constructors formal parameter types, in declared
191      * order. If params is null, it is treated as if it were an empty
192      * array.
193      *
194      * @param cls the class to search for a matching constructor
195      * @param params the array of parameters that will be used to
196      * invoke the constructor
197      * @return the Method object of the public constructor that
198      * matches the above
199      * @see java.lang.Class#getConstructor(Class[])
200      **/

201     public static Constructor JavaDoc getConstructor(Class JavaDoc cls, Object JavaDoc[] params)
202     {
203         Constructor JavaDoc[] constructors = cls.getConstructors();
204
205         for (int i = 0; i < constructors.length; ++i )
206         {
207             Class JavaDoc[] parameterTypes = constructors[i].getParameterTypes();
208
209             // The methods we are trying to compare must
210
// the same number of arguments.
211
if (parameterTypes.length == params.length)
212             {
213                 // Make sure the given parameter is a valid
214
// subclass of the method parameter in question.
215
for (int j = 0; ; j++)
216                 {
217                     if (j >= parameterTypes.length)
218                         return constructors[i]; // found
219

220                     Class JavaDoc c = parameterTypes[j];
221                     Object JavaDoc p = params[j];
222                     if ( c.isPrimitive() )
223                     {
224                         try
225                         {
226                             if ( c != p.getClass().getField("TYPE").get(p) )
227                                 break;
228                         } catch (Exception JavaDoc ex) {
229                             break; // p is not a primitive derivate
230
}
231                     }
232                     else if ( (p != null) &&
233                               !c.isAssignableFrom( p.getClass() ) )
234                         break;
235                 } // for all parameters
236
} // if same length
237
} // for all contructors
238

239         return null;
240     }
241     
242     public ModuleManager getModuleManager()
243     {
244         return fieldModuleManager;
245     }
246 }
247
Popular Tags