KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > methodhead > sitecontext > SiteContext


1 /*
2  * Copyright (C) 2006 Methodhead Software LLC. All rights reserved.
3  *
4  * This file is part of TransferCM.
5  *
6  * TransferCM is free software; you can redistribute it and/or modify it under the
7  * terms of the GNU General Public License as published by the Free Software
8  * Foundation; either version 2 of the License, or (at your option) any later
9  * version.
10  *
11  * TransferCM is distributed in the hope that it will be useful, but WITHOUT ANY
12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License along with
17  * TransferCM; if not, write to the Free Software Foundation, Inc., 51 Franklin St,
18  * Fifth Floor, Boston, MA 02110-1301 USA
19  */

20
21 package com.methodhead.sitecontext;
22
23 import java.sql.SQLException JavaDoc;
24 import java.sql.ResultSet JavaDoc;
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26
27 import com.methodhead.persistable.ConnectionSingleton;
28 import com.methodhead.persistable.Persistable;
29 import com.methodhead.persistable.PersistableException;
30 import com.methodhead.persistable.Key;
31 import com.methodhead.MhfException;
32 import com.methodhead.event.Event;
33 import com.methodhead.aikp.IntKey;
34 import com.methodhead.aikp.AutoIntKeyPersistable;
35
36 import java.util.List JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Iterator JavaDoc;
39 import java.util.Collections JavaDoc;
40
41 import org.apache.commons.beanutils.DynaClass;
42 import org.apache.commons.beanutils.DynaProperty;
43 import org.apache.commons.beanutils.BasicDynaClass;
44 import org.apache.log4j.Logger;
45 import org.apache.commons.lang.exception.ExceptionUtils;
46
47
48 /**
49  * A SiteContext. The following fields are defined:
50  * <ul>
51  * <li><tt>int id = 0</tt></li>
52  * <li><tt>int path = ""</tt></li>
53  * </ul>
54  */

55 public class SiteContext
56 extends
57   AutoIntKeyPersistable
58 implements
59   Comparable JavaDoc {
60
61   private static DynaClass dynaClass_ = null;
62   private static DynaClass domainDynaClass_ = null;
63
64   static {
65     DynaProperty[] dynaProperties =
66       new DynaProperty[] {
67         new DynaProperty( "id", Integer JavaDoc.class ),
68         new DynaProperty( "path", String JavaDoc.class )
69       };
70
71     dynaClass_ =
72       new BasicDynaClass(
73         "mh_sitecontext", SiteContext.class, dynaProperties );
74
75     dynaProperties =
76       new DynaProperty[] {
77         new DynaProperty( "sitecontext_id", Integer JavaDoc.class ),
78         new DynaProperty( "name", String JavaDoc.class ),
79         new DynaProperty( "rank", Integer JavaDoc.class )
80       };
81
82     domainDynaClass_ =
83       new BasicDynaClass(
84         "mh_domain", Persistable.class, dynaProperties );
85   }
86
87   // constructors /////////////////////////////////////////////////////////////
88

89   public SiteContext() {
90     super( dynaClass_ );
91     init();
92   }
93
94   public SiteContext( DynaClass dynaClass ) {
95     super( dynaClass );
96     init();
97   }
98
99   // constants ////////////////////////////////////////////////////////////////
100

101   public static final String JavaDoc SITECONTEXT_KEY =
102     "com.methodhead.sitecontext.SITECONTEXT_KEY";
103
104   public static final String JavaDoc DEFAULTDOMAIN =
105     "DEFAULT";
106
107   // classes //////////////////////////////////////////////////////////////////
108

109   // methods //////////////////////////////////////////////////////////////////
110

111   /**
112    * Returns a human-readable representation of this site context.
113    */

114   public String JavaDoc toString() {
115     if ( domains_.isEmpty() )
116       return "SiteContext (no domains)";
117
118     if ( "".equals( getString( "path" ) ) )
119       return ( String JavaDoc )domains_.get( 0 );
120
121     return domains_.get( 0 ) + "/" + getString( "path" );
122   }
123
124   /**
125    * Returns <tt>true</tt> if <tt>o</tt> is a <tt>SiteContext</tt> and has the
126    * same id as this object.
127    */

128   public boolean equals(
129     Object JavaDoc o ) {
130
131     if ( ( o != null ) && ( o instanceof SiteContext ) )
132       return ( ( SiteContext )o ).getInt( "id" ) == getInt( "id" );
133
134     return false;
135   }
136
137   /**
138    * Returns this site context's id.
139    */

140   public int hashCode() {
141     return getInt( "id" );
142   }
143
144   /**
145    * Compares this site context using the name of the first domain, if any, and
146    * then any path.
147    */

148   public int compareTo(
149     Object JavaDoc o ) {
150
151     if ( !( o instanceof SiteContext ) )
152       return -1;
153
154     SiteContext sc = ( SiteContext )o;
155
156     if ( getDomains().size() == 0 ) {
157       if ( sc.getDomains().size() > 0 )
158         return -1;
159       else
160         return getString( "path" ).compareTo( sc.getString( "path" ) );
161     }
162     else {
163       if ( sc.getDomains().size() == 0 )
164         return 1;
165       else {
166         if ( getDomains().get( 0 ).equals( sc.getDomains().get( 0 ) ) )
167           return getString( "path" ).compareTo( sc.getString( "path" ) );
168         else
169           return
170             ( ( String JavaDoc )getDomains().get( 0 ) ).compareTo(
171               sc.getDomains().get( 0 ) );
172       }
173     }
174   }
175
176   /**
177    * Initializes site context fields.
178    */

179   protected void init() {
180     setInt( "id", 0 );
181     setString( "path", "" );
182   }
183
184   /**
185    * Deletes any domains associated with this site context from the database.
186    */

187   private void deleteDomains() {
188     Persistable.deleteAll(
189       domainDynaClass_, "sitecontext_id=" + getInt( "id" ) );
190   }
191
192   /**
193    * Saves any domains associated with this site context to the database.
194    */

195   private void saveDomains() {
196     Persistable p = new Persistable( domainDynaClass_ );
197     p.setInt( "sitecontext_id", getInt( "id" ) );
198
199     int i = 0;
200     for ( Iterator JavaDoc iter = domains_.iterator(); iter.hasNext(); ) {
201       p.set( "name", iter.next() );
202       p.setInt( "rank", i++ );
203       p.saveNew();
204     }
205   }
206
207   /**
208    * Loads any domains associated with this site context from the database.
209    */

210   private void loadDomains() {
211     domains_.clear();
212
213     List JavaDoc l =
214       Persistable.loadAll(
215         domainDynaClass_, "sitecontext_id=" + getInt( "id" ), "rank" );
216
217     for ( Iterator JavaDoc iter = l.iterator(); iter.hasNext(); ) {
218       Persistable p = ( Persistable )iter.next();
219       domains_.add( p.get( "name" ) );
220     }
221   }
222
223   public void saveNew() {
224     super.saveNew();
225     saveDomains();
226   }
227
228   public void save() {
229     super.save();
230     deleteDomains();
231     saveDomains();
232   }
233
234   public void load(
235     Key key ) {
236     super.load( key );
237     loadDomains();
238   }
239
240   /**
241    * Loads the context for <tt>domain</tt> and <tt>path</tt>, returning
242    * <tt>true</tt> if it was successfully loaded, or <tt>false</tt> if no such
243    * context exists.
244    */

245   public boolean loadForDomainAndPath(
246     String JavaDoc domain,
247     String JavaDoc path ) {
248
249     String JavaDoc sql =
250       "SELECT " +
251       " sc.id AS id " +
252       "FROM " +
253       " mh_sitecontext AS sc " +
254       "LEFT JOIN " +
255       " mh_domain AS d ON " +
256       " d.sitecontext_id = sc.id " +
257       "WHERE " +
258       " sc.path=" + getSqlLiteral( path ) + " AND " +
259       " d.name=" + getSqlLiteral( domain ) + " ";
260
261     ResultSet JavaDoc rs = null;
262     try {
263       rs = ConnectionSingleton.runQuery( sql );
264
265       if ( !rs.next() ) {
266         return false;
267       }
268
269       load( new IntKey( rs.getInt( "id" ) ) );
270         
271       return true;
272     }
273     catch ( SQLException JavaDoc e ) {
274       String JavaDoc msg = "Loading SiteContext for domain \"" + domain + "\" and path \"" + path + "\". " + ExceptionUtils.getStackTrace( e );
275       logger_.error( msg );
276       throw new RuntimeException JavaDoc( msg );
277     }
278     finally {
279       ConnectionSingleton.close( rs );
280     }
281   }
282
283   /**
284    * Deletes this site context and any events associated with it.
285    */

286   public void delete() {
287     deleteDomains();
288     Event event = new Event();
289     event.setSiteContext( this );
290     event.deleteAll();
291     super.delete();
292   }
293
294   /**
295    * Returns the default site context, creating it in the database if
296    * necessary. The default context always has id <tt>0</tt>. If this method
297    * ends up creating the default context, it won't create any domains for it,
298    * nor will it set a path.
299    */

300   public static SiteContext getDefaultContext() {
301     SiteContext siteContext = new SiteContext();
302
303     try {
304       siteContext.load( new IntKey( 0 ) );
305     }
306     catch ( PersistableException e ) {
307       //
308
// can't use saveNew() because this is a aikp and that will result in an
309
// id other than 0; we have to manually insert the context
310
//
311
String JavaDoc sql =
312         "INSERT INTO " +
313         " mh_sitecontext " +
314         "( " +
315         " id, " +
316         " path ) " +
317         "VALUES ( " +
318         " 0, " +
319         " '' " +
320         ")";
321
322       try {
323         ConnectionSingleton.runUpdate( sql );
324       }
325       catch ( SQLException JavaDoc se ) {
326         throw new PersistableException(
327           "Unexpected SQLException: " + se.getMessage() );
328       }
329
330       siteContext.getDomains().add( DEFAULTDOMAIN );
331       siteContext.save();
332     }
333
334     return siteContext;
335   }
336
337   /**
338    * Sets the site context in the session.
339    */

340   public static void setContext(
341     HttpServletRequest JavaDoc request,
342     SiteContext context ) {
343
344     request.getSession().setAttribute( SITECONTEXT_KEY, context );
345   }
346
347   /**
348    * Gets the site context, looking first in the session, then in the request
349    * (NEEDS UNIT TESTING). Returns <tt>null</tt> if no site context is found.
350    */

351   public static SiteContext getContext(
352     HttpServletRequest JavaDoc request ) {
353
354     SiteContext context = ( SiteContext )request.getSession().getAttribute( SITECONTEXT_KEY );
355
356     if ( context == null ) {
357       context = ( SiteContext )request.getAttribute( SITECONTEXT_KEY );
358     }
359       
360     return context;
361   }
362
363   /**
364    * Loads all site contexts in the database, sorted according to the order
365    * specified by {@link #compareTo compareTo()}.
366    */

367   public static List JavaDoc loadAll() {
368     List JavaDoc list = loadAll( dynaClass_, null, null );
369
370     for ( Iterator JavaDoc iter = list.iterator(); iter.hasNext(); ) {
371       SiteContext sc = ( SiteContext )iter.next();
372       sc.load( new IntKey( sc.getInt( "id" ) ) );
373     }
374
375     Collections.sort( list );
376
377     return list;
378   }
379
380   // properties ///////////////////////////////////////////////////////////////
381

382   /**
383    * Returns the site context's domains as a list of <tt>String</tt>s.
384    */

385   public List JavaDoc getDomains() {
386     return domains_;
387   }
388
389   // attributes ///////////////////////////////////////////////////////////////
390

391   protected List JavaDoc domains_ = new ArrayList JavaDoc();
392
393   private static Logger logger_ = Logger.getLogger( SiteContext.class );
394 }
395
Popular Tags