KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > core > Context


1 /*
2  * Context.java
3  *
4  * Version: $Revision: 1.21 $
5  *
6  * Date: $Date: 2006/11/07 22:41:33 $
7  *
8  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
9  * Institute of Technology. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are
13  * met:
14  *
15  * - Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * - Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution.
21  *
22  * - Neither the name of the Hewlett-Packard Company nor the name of the
23  * Massachusetts Institute of Technology nor the names of their
24  * contributors may be used to endorse or promote products derived from
25  * this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  */

40 package org.dspace.core;
41
42 import java.sql.Connection JavaDoc;
43 import java.sql.SQLException JavaDoc;
44 import java.util.ArrayList JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.Map JavaDoc;
49
50 import org.apache.log4j.Logger;
51 import org.dspace.eperson.EPerson;
52 import org.dspace.eperson.Group;
53 import org.dspace.storage.rdbms.DatabaseManager;
54
55 /**
56  * Class representing the context of a particular DSpace operation. This stores
57  * information such as the current authenticated user and the database
58  * connection being used.
59  * <P>
60  * Typical use of the context object will involve constructing one, and setting
61  * the current user if one is authenticated. Several operations may be performed
62  * using the context object. If all goes well, <code>complete</code> is called
63  * to commit the changes and free up any resources used by the context. If
64  * anything has gone wrong, <code>abort</code> is called to roll back any
65  * changes and free up the resources.
66  * <P>
67  * The context object is also used as a cache for CM API objects.
68  *
69  *
70  * @author Robert Tansley
71  * @version $Revision: 1.21 $
72  */

73 public class Context
74 {
75     private static final Logger log = Logger.getLogger(Context.class);
76
77     /** Database connection */
78     private Connection JavaDoc connection;
79
80     /** Current user - null means anonymous access */
81     private EPerson currentUser;
82
83     /** Extra log info */
84     private String JavaDoc extraLogInfo;
85
86     /** Indicates whether authorisation subsystem should be ignored */
87     private boolean ignoreAuth;
88
89     /** Object cache for this context */
90     private Map JavaDoc objectCache;
91
92     /** Group IDs of special groups user is a member of */
93     private List JavaDoc specialGroups;
94
95     /**
96      * Construct a new context object. A database connection is opened. No user
97      * is authenticated.
98      *
99      * @exception SQLException
100      * if there was an error obtaining a database connection
101      */

102     public Context() throws SQLException JavaDoc
103     {
104         // Obtain a non-auto-committing connection
105
connection = DatabaseManager.getConnection();
106         connection.setAutoCommit(false);
107
108         currentUser = null;
109         extraLogInfo = "";
110         ignoreAuth = false;
111
112         objectCache = new HashMap JavaDoc();
113         specialGroups = new ArrayList JavaDoc();
114     }
115
116     /**
117      * Get the database connection associated with the context
118      *
119      * @return the database connection
120      */

121     public Connection JavaDoc getDBConnection()
122     {
123         return connection;
124     }
125
126     /**
127      * Set the current user. Authentication must have been performed by the
128      * caller - this call does not attempt any authentication.
129      *
130      * @param user
131      * the new current user, or <code>null</code> if no user is
132      * authenticated
133      */

134     public void setCurrentUser(EPerson user)
135     {
136         currentUser = user;
137     }
138
139     /**
140      * Get the current (authenticated) user
141      *
142      * @return the current user, or <code>null</code> if no user is
143      * authenticated
144      */

145     public EPerson getCurrentUser()
146     {
147         return currentUser;
148     }
149
150     /**
151      * Find out if the authorisation system should be ignored for this context.
152      *
153      * @return <code>true</code> if authorisation should be ignored for this
154      * session.
155      */

156     public boolean ignoreAuthorization()
157     {
158         return ignoreAuth;
159     }
160
161     /**
162      * Specify whether the authorisation system should be ignored for this
163      * context. This should be used sparingly.
164      *
165      * @param b
166      * if <code>true</code>, authorisation should be ignored for
167      * this session.
168      */

169     public void setIgnoreAuthorization(boolean b)
170     {
171         ignoreAuth = b;
172     }
173
174     /**
175      * Set extra information that should be added to any message logged in the
176      * scope of this context. An example of this might be the session ID of the
177      * current Web user's session:
178      * <P>
179      * <code>setExtraLogInfo("session_id="+request.getSession().getId());</code>
180      *
181      * @param info
182      * the extra information to log
183      */

184     public void setExtraLogInfo(String JavaDoc info)
185     {
186         extraLogInfo = info;
187     }
188
189     /**
190      * Get extra information to be logged with message logged in the scope of
191      * this context.
192      *
193      * @return the extra log info - guaranteed non- <code>null</code>
194      */

195     public String JavaDoc getExtraLogInfo()
196     {
197         return extraLogInfo;
198     }
199
200     /**
201      * Close the context object after all of the operations performed in the
202      * context have completed succesfully. Any transaction with the database is
203      * committed.
204      *
205      * @exception SQLException
206      * if there was an error completing the database transaction
207      * or closing the connection
208      */

209     public void complete() throws SQLException JavaDoc
210     {
211         // FIXME: Might be good not to do a commit() if nothing has actually
212
// been written using this connection
213
try
214         {
215             // Commit any changes made as part of the transaction
216
connection.commit();
217         }
218         finally
219         {
220             // Free the connection
221
DatabaseManager.freeConnection(connection);
222             connection = null;
223         }
224     }
225
226     /**
227      * Commit any transaction that is currently in progress, but do not close
228      * the context.
229      *
230      * @exception SQLException
231      * if there was an error completing the database transaction
232      * or closing the connection
233      */

234     public void commit() throws SQLException JavaDoc
235     {
236         // Commit any changes made as part of the transaction
237
connection.commit();
238     }
239
240     /**
241      * Close the context, without committing any of the changes performed using
242      * this context. The database connection is freed. No exception is thrown if
243      * there is an error freeing the database connection, since this method may
244      * be called as part of an error-handling routine where an SQLException has
245      * already been thrown.
246      */

247     public void abort()
248     {
249         try
250         {
251             connection.rollback();
252         }
253         catch (SQLException JavaDoc se)
254         {
255             log.error(se.getMessage());
256             se.printStackTrace();
257         }
258         finally
259         {
260             DatabaseManager.freeConnection(connection);
261             connection = null;
262         }
263     }
264
265     /**
266      * Find out if this context is valid. Returns <code>false</code> if this
267      * context has been aborted or completed.
268      *
269      * @return <code>true</code> if the context is still valid, otherwise
270      * <code>false</code>
271      */

272     public boolean isValid()
273     {
274         // Only return true if our DB connection is live
275
return (connection != null);
276     }
277
278     /**
279      * Store an object in the object cache.
280      *
281      * @param objectClass
282      * Java Class of object to check for in cache
283      * @param id
284      * ID of object in cache
285      *
286      * @return the object from the cache, or <code>null</code> if it's not
287      * cached.
288      */

289     public Object JavaDoc fromCache(Class JavaDoc objectClass, int id)
290     {
291         String JavaDoc key = objectClass.getName() + id;
292
293         return objectCache.get(key);
294     }
295
296     /**
297      * Store an object in the object cache.
298      *
299      * @param o
300      * the object to store
301      * @param id
302      * the object's ID
303      */

304     public void cache(Object JavaDoc o, int id)
305     {
306         String JavaDoc key = o.getClass().getName() + id;
307         objectCache.put(key, o);
308     }
309
310     /**
311      * Remove an object from the object cache.
312      *
313      * @param o
314      * the object to remove
315      * @param id
316      * the object's ID
317      */

318     public void removeCached(Object JavaDoc o, int id)
319     {
320         String JavaDoc key = o.getClass().getName() + id;
321         objectCache.remove(key);
322     }
323
324     /**
325      * set membership in a special group
326      *
327      * @param groupID
328      * special group's ID
329      */

330     public void setSpecialGroup(int groupID)
331     {
332         specialGroups.add(new Integer JavaDoc(groupID));
333
334         // System.out.println("Added " + groupID);
335
}
336
337     /**
338      * test if member of special group
339      *
340      * @param groupID
341      * ID of special group to test
342      * @return true if member
343      */

344     public boolean inSpecialGroup(int groupID)
345     {
346         if (specialGroups.contains(new Integer JavaDoc(groupID)))
347         {
348             // System.out.println("Contains " + groupID);
349
return true;
350         }
351
352         return false;
353     }
354
355     /**
356      * gets an array of all of the special groups that current user is a member
357      * of
358      *
359      * @return
360      * @throws SQLException
361      */

362     public Group[] getSpecialGroups() throws SQLException JavaDoc
363     {
364         List JavaDoc myGroups = new ArrayList JavaDoc();
365
366         Iterator JavaDoc i = specialGroups.iterator();
367
368         while (i.hasNext())
369         {
370             myGroups.add(Group.find(this, ((Integer JavaDoc) i.next()).intValue()));
371         }
372
373         return (Group[]) myGroups.toArray(new Group[0]);
374     }
375
376     protected void finalize()
377     {
378         /*
379          * If a context is garbage-collected, we roll back and free up the
380          * database connection if there is one.
381          */

382         if (connection != null)
383         {
384             abort();
385         }
386     }
387 }
388
Popular Tags