KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > slide > store > mem > AbstractTransientStore


1 /*
2  * $Header: /home/cvs/jakarta-slide/src/stores/org/apache/slide/store/mem/AbstractTransientStore.java,v 1.3.2.1 2004/09/28 11:34:23 luetzkendorf Exp $
3  * $Revision: 1.3.2.1 $
4  * $Date: 2004/09/28 11:34:23 $
5  *
6  * ====================================================================
7  *
8  * Copyright 1999-2002 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  *
22  */

23 package org.apache.slide.store.mem;
24
25 import java.lang.reflect.Constructor JavaDoc;
26 import java.lang.reflect.InvocationTargetException JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.NoSuchElementException JavaDoc;
34
35 import javax.transaction.xa.XAException JavaDoc;
36 import javax.transaction.xa.XAResource JavaDoc;
37 import javax.transaction.xa.Xid JavaDoc;
38
39 import org.apache.commons.transaction.memory.ConflictException;
40 import org.apache.commons.transaction.memory.TransactionalMapWrapper;
41 import org.apache.commons.transaction.memory.jca.MapXAResource;
42 import org.apache.commons.transaction.util.LoggerFacade;
43
44 import org.apache.slide.common.AbstractServiceBase;
45 import org.apache.slide.common.NamespaceAccessToken;
46 import org.apache.slide.common.ServiceAccessException;
47 import org.apache.slide.common.ServiceConnectionFailedException;
48 import org.apache.slide.common.ServiceDisconnectionFailedException;
49 import org.apache.slide.common.ServiceInitializationFailedException;
50 import org.apache.slide.common.ServiceParameterErrorException;
51 import org.apache.slide.common.ServiceParameterMissingException;
52 import org.apache.slide.common.ServiceResetFailedException;
53 import org.apache.slide.util.logger.Logger;
54 import org.apache.slide.util.logger.TxLogger;
55
56 /**
57  * Base class for the stores that what to store its data transient in a
58  * map.
59  *
60  * <p>Implementations access the backing map only via {@link #put(Object, Object)},
61  * {@link #get(Object)} and {@link #remove(Object)}.
62  *
63  * <p>The backed map can be any class that is derived from
64  * {@link org.apache.commons.transaction.memory.TransactionalMapWrapper}.
65  *
66  * <p>The class may be configured in the <code>domain.xml</code> using the
67  * parameter <code>map-classname</code>.
68  * Default is {@link org.apache.commons.transaction.memory.OptimisticMapWrapper}.
69  *
70  *
71  */

72 public abstract class AbstractTransientStore extends AbstractServiceBase {
73    
74    static final String JavaDoc MAP_IMPL_PARAMETER = "map-classname";
75    static final String JavaDoc MAP_IMPL_PARAMETER_DEFAULT =
76       "org.apache.commons.transaction.memory.OptimisticMapWrapper";
77    
78    private Map JavaDoc parameters = null;
79    private boolean isConnected = false;
80    
81    /**
82     * The map containing the stored content.
83     */

84    private TransactionalMapWrapper store = null;
85
86    /**
87     * The XAResource to delegate all XA requests.
88     */

89    private MapXAResource xaResource = null;
90
91    // ----------------------------------------------------- XAResource Mathods
92

93    public void start(Xid JavaDoc xid, int flags)
94       throws XAException JavaDoc
95    {
96       debug("start {0} {1}", xid, Integer.toString(flags));
97       this.xaResource.start(xid, flags);
98    }
99    
100    public void commit(Xid JavaDoc xid, boolean onePhase)
101       throws XAException JavaDoc
102    {
103       debug("commit {0} {1}", xid, onePhase ? "true" : "false");
104       try {
105          this.xaResource.commit(xid, onePhase);
106       }
107       catch (ConflictException e) {
108          this.xaResource.rollback(xid);
109          // TODO it would be great if we could throw something
110
// that would (on the webdav layer) leads to a 409 Conflict
111
// instead of 500 Internal Server Error
112
throw new XAException JavaDoc(XAException.XA_RBOTHER); // ??
113
}
114    }
115    
116    public int prepare(Xid JavaDoc xid)
117       throws XAException JavaDoc
118    {
119       debug("prepare {0}", xid);
120       return this.xaResource.prepare(xid);
121    }
122
123    public void end(Xid JavaDoc xid, int flags)
124        throws XAException JavaDoc
125    {
126       debug("end {0} {1}", xid, Integer.toString(flags));
127       this.xaResource.end(xid, flags);
128    }
129    
130    public void rollback(Xid JavaDoc xid)
131        throws XAException JavaDoc
132    {
133       debug("rollback {0}", xid);
134       this.xaResource.rollback(xid);
135    }
136    
137    public Xid JavaDoc[] recover(int flag)
138       throws XAException JavaDoc
139    {
140       debug("recover {0}", Integer.toString(flag));
141       return this.xaResource.recover(flag);
142    }
143
144    public void forget(Xid JavaDoc xid)
145        throws XAException JavaDoc
146    {
147        debug("forget {0}", xid);
148        this.xaResource.forget(xid);
149    }
150    
151    public int getTransactionTimeout()
152        throws XAException JavaDoc
153    {
154        return this.xaResource.getTransactionTimeout();
155    }
156
157    public boolean setTransactionTimeout(int seconds)
158        throws XAException JavaDoc
159    {
160        return this.xaResource.setTransactionTimeout(seconds);
161    }
162    
163    public boolean isSameRM(XAResource JavaDoc xares)
164        throws XAException JavaDoc
165    {
166       return this == xares;
167    }
168    
169    
170    
171
172    // ------------------------------------- Store accessors for implementations
173

174    protected void put(Object JavaDoc key, Object JavaDoc value) {
175       this.store.put(key, value);
176    }
177    
178    protected Object JavaDoc get(Object JavaDoc key) {
179       return this.store.get(key);
180    }
181    
182    protected Object JavaDoc remove(Object JavaDoc key) {
183       return this.store.remove(key);
184    }
185    
186    // ------------------------------------------------ ContextTuple InnerClass
187

188    public void setParameters(Hashtable JavaDoc parameters)
189          throws ServiceParameterErrorException,
190                 ServiceParameterMissingException
191    {
192       this.parameters = new HashMap JavaDoc(parameters);
193    }
194    
195    protected String JavaDoc getParameter(String JavaDoc name) {
196       if (this.parameters != null) {
197          return (String JavaDoc)this.parameters.get(name);
198       } else {
199          throw new IllegalStateException JavaDoc("Parameter not yet set!");
200       }
201    }
202    public void initialize(NamespaceAccessToken token)
203       throws ServiceInitializationFailedException
204    {
205       super.initialize(token);
206       
207       TxLogger txLogger = new TxLogger(getLogger(), LogChannel());
208       
209       String JavaDoc param = (String JavaDoc)this.parameters.get(MAP_IMPL_PARAMETER);
210       if (param == null) {
211          param = MAP_IMPL_PARAMETER_DEFAULT;
212       }
213       try {
214          info("Initializing {0} using {1}.", getClass().getName(), param);
215          Map JavaDoc toBeWrapped = new HashMap JavaDoc();
216          Class JavaDoc mapClass = Class.forName(param);
217          
218          try {
219             Class JavaDoc[] ctorFormalArgs = { Map JavaDoc.class, LoggerFacade.class };
220             Constructor JavaDoc ctor = mapClass.getConstructor(ctorFormalArgs);
221             Object JavaDoc[] ctorArgs = { toBeWrapped, txLogger };
222             this.store = (TransactionalMapWrapper)ctor.newInstance(ctorArgs);
223          }
224          catch (NoSuchMethodException JavaDoc e) {
225             // try next
226
try {
227                Class JavaDoc[] ctorFormalArgs = { Map JavaDoc.class };
228                Constructor JavaDoc ctor = mapClass.getConstructor(ctorFormalArgs);
229                Object JavaDoc[] ctorArgs = { toBeWrapped };
230                this.store = (TransactionalMapWrapper)ctor.newInstance(ctorArgs);
231             }
232             catch (NoSuchMethodException JavaDoc ee) {
233                error("Initialization error: ", ee);
234                throw new ServiceInitializationFailedException(this, ee);
235             }
236          }
237       }
238       catch (ClassNotFoundException JavaDoc e) {
239          error("Initialization error: ", e);
240          throw new ServiceInitializationFailedException(this, e);
241       }
242       catch (InstantiationException JavaDoc e) {
243          error("Initialization error: ", e);
244          throw new ServiceInitializationFailedException(this, e);
245       }
246       catch (IllegalAccessException JavaDoc e) {
247          error("Initialization error: ", e);
248          throw new ServiceInitializationFailedException(this, e);
249       }
250       catch (InvocationTargetException JavaDoc e) {
251          error("Initialization error: ", e);
252          throw new ServiceInitializationFailedException(this, e);
253       }
254       catch (ClassCastException JavaDoc e) {
255          error("Initialization error: ", e);
256          throw new ServiceInitializationFailedException(this,
257                "class in parameter '" + MAP_IMPL_PARAMETER + "' must " +
258                      "be derived from TransactionalMapWrapper");
259       }
260       
261       this.xaResource = new MapXAResource(this.store);
262       // FIXME can't set logging because methods are not public, and
263
// ctor doesn't take a loggerFacade
264
}
265
266    public void connect() throws ServiceConnectionFailedException {
267       this.isConnected = true;
268    }
269    public void disconnect() throws ServiceDisconnectionFailedException {
270       this.isConnected = false;
271    }
272    public void reset() throws ServiceResetFailedException {
273    }
274    public boolean isConnected() throws ServiceAccessException {
275       return this.isConnected;
276    }
277    
278
279    // -------------------------------------------------------------------
280

281    
282    protected String JavaDoc LogChannel() {
283       return LOG_CHANNEL;
284    }
285    protected void debug(String JavaDoc msg, Object JavaDoc o) {
286      if (this.getLogger().isEnabled(Logger.DEBUG)) {
287         Object JavaDoc[] args = { o };
288         this.getLogger().log(MessageFormat.format(msg, args),
289                              LogChannel(), Logger.DEBUG);
290      }
291    }
292    protected void debug(String JavaDoc msg, Object JavaDoc o1, Object JavaDoc o2) {
293      if (this.getLogger().isEnabled(Logger.DEBUG)) {
294         Object JavaDoc[] args = { o1, o2 };
295         this.getLogger().log(MessageFormat.format(msg, args),
296                              LogChannel(), Logger.DEBUG);
297      }
298    }
299    private void info(String JavaDoc msg, Object JavaDoc o1, Object JavaDoc o2) {
300       if (this.getLogger().isEnabled(Logger.INFO)) {
301          Object JavaDoc[] args = { o1, o2 };
302          this.getLogger().log(MessageFormat.format(msg, args),
303                               LogChannel(), Logger.INFO);
304       }
305    }
306    private void error(String JavaDoc msg, Throwable JavaDoc t) {
307       if (this.getLogger().isEnabled(Logger.INFO)) {
308          this.getLogger().log(msg, t,
309                               LogChannel(), Logger.INFO);
310       }
311    }
312    
313    /**
314     * Empty enumeration.
315     */

316    protected static Enumeration JavaDoc EMPTY_ENUM = new Enumeration JavaDoc() {
317       public boolean hasMoreElements() {
318          return false;
319       }
320       public Object JavaDoc nextElement() {
321          throw new NoSuchElementException JavaDoc();
322       }
323    };
324    
325    /**
326     * Enumeration wrapper for an Iterator.
327     */

328    protected static class IteratorEnum implements Enumeration JavaDoc {
329       private Iterator JavaDoc iterator;
330       public IteratorEnum(Iterator JavaDoc iterator){
331          this.iterator = iterator;
332       }
333       public boolean hasMoreElements() {
334          return this.iterator.hasNext();
335       }
336       public Object JavaDoc nextElement() {
337          return this.iterator.next();
338       }
339    }
340 }
341
Popular Tags