001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.transaction;
018    
019    import java.io.IOException;
020    import java.io.InterruptedIOException;
021    import java.util.ArrayList;
022    import java.util.Collections;
023    import java.util.Iterator;
024    import java.util.concurrent.Callable;
025    import java.util.concurrent.ExecutionException;
026    import java.util.concurrent.FutureTask;
027    import javax.transaction.xa.XAException;
028    import org.apache.activemq.command.TransactionId;
029    import org.slf4j.Logger;
030    
031    /**
032     * Keeps track of all the actions the need to be done when a transaction does a
033     * commit or rollback.
034     * 
035     * 
036     */
037    public abstract class Transaction {
038    
039        public static final byte START_STATE = 0; // can go to: 1,2,3
040        public static final byte IN_USE_STATE = 1; // can go to: 2,3
041        public static final byte PREPARED_STATE = 2; // can go to: 3
042        public static final byte FINISHED_STATE = 3;
043    
044        private final ArrayList<Synchronization> synchronizations = new ArrayList<Synchronization>();
045        private byte state = START_STATE;
046        protected FutureTask<?> preCommitTask = new FutureTask<Object>(new Callable<Object>() {
047            public Object call() throws Exception {
048                doPreCommit();
049                return null;
050            }   
051        });
052        protected FutureTask<?> postCommitTask = new FutureTask<Object>(new Callable<Object>() {
053            public Object call() throws Exception {
054                doPostCommit();
055                return null;
056            }   
057        });
058        
059        public byte getState() {
060            return state;
061        }
062    
063        public void setState(byte state) {
064            this.state = state;
065        }
066    
067        public void addSynchronization(Synchronization r) {
068            synchronizations.add(r);
069            if (state == START_STATE) {
070                state = IN_USE_STATE;
071            }
072        }
073    
074        public Synchronization findMatching(Synchronization r) {
075            int existing = synchronizations.indexOf(r);
076            if (existing != -1) {
077                return synchronizations.get(existing);
078            }
079            return null;
080        }
081    
082        public void removeSynchronization(Synchronization r) {
083            synchronizations.remove(r);
084        }
085    
086        public void prePrepare() throws Exception {
087    
088            // Is it ok to call prepare now given the state of the
089            // transaction?
090            switch (state) {
091            case START_STATE:
092            case IN_USE_STATE:
093                break;
094            default:
095                XAException xae = new XAException("Prepare cannot be called now.");
096                xae.errorCode = XAException.XAER_PROTO;
097                throw xae;
098            }
099    
100            // // Run the prePrepareTasks
101            // for (Iterator iter = prePrepareTasks.iterator(); iter.hasNext();) {
102            // Callback r = (Callback) iter.next();
103            // r.execute();
104            // }
105        }
106        
107        protected void fireBeforeCommit() throws Exception {
108            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
109                Synchronization s = iter.next();
110                s.beforeCommit();
111            }
112        }
113    
114        protected void fireAfterCommit() throws Exception {
115            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
116                Synchronization s = iter.next();
117                s.afterCommit();
118            }
119        }
120    
121        public void fireAfterRollback() throws Exception {
122            Collections.reverse(synchronizations);
123            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
124                Synchronization s = iter.next();
125                s.afterRollback();
126            }
127        }
128    
129        @Override
130        public String toString() {
131            return super.toString() + "[synchronizations=" + synchronizations + "]";
132        }
133    
134        public abstract void commit(boolean onePhase) throws XAException, IOException;
135    
136        public abstract void rollback() throws XAException, IOException;
137    
138        public abstract int prepare() throws XAException, IOException;
139    
140        public abstract TransactionId getTransactionId();
141    
142        public abstract Logger getLog();
143        
144        public boolean isPrepared() {
145            return getState() == PREPARED_STATE;
146        }
147        
148        public int size() {
149            return synchronizations.size();
150        }
151        
152        protected void waitPostCommitDone(FutureTask<?> postCommitTask) throws XAException, IOException {
153            try {
154                postCommitTask.get();
155            } catch (InterruptedException e) {
156                throw new InterruptedIOException(e.toString());
157            } catch (ExecutionException e) {
158                Throwable t = e.getCause();
159                if (t instanceof XAException) {
160                    throw (XAException) t;
161                } else if (t instanceof IOException) {
162                    throw (IOException) t;
163                } else {
164                    throw new XAException(e.toString());
165                }
166            }    
167        }
168        
169        protected void doPreCommit() throws XAException {
170            try {
171                fireBeforeCommit();
172            } catch (Throwable e) {
173                // I guess this could happen. Post commit task failed
174                // to execute properly.
175                getLog().warn("PRE COMMIT FAILED: ", e);
176                XAException xae = new XAException("PRE COMMIT FAILED");
177                xae.errorCode = XAException.XAER_RMERR;
178                xae.initCause(e);
179                throw xae;
180            }
181        }
182    
183        protected void doPostCommit() throws XAException {
184            try {
185                fireAfterCommit();
186            } catch (Throwable e) {
187                // I guess this could happen. Post commit task failed
188                // to execute properly.
189                getLog().warn("POST COMMIT FAILED: ", e);
190                XAException xae = new XAException("POST COMMIT FAILED");
191                xae.errorCode = XAException.XAER_RMERR;
192                xae.initCause(e);
193                throw xae;
194            }
195        }
196    }