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        boolean committed = false;
044    
045        private final ArrayList<Synchronization> synchronizations = new ArrayList<Synchronization>();
046        private byte state = START_STATE;
047        protected FutureTask<?> preCommitTask = new FutureTask<Object>(new Callable<Object>() {
048            public Object call() throws Exception {
049                doPreCommit();
050                return null;
051            }   
052        });
053        protected FutureTask<?> postCommitTask = new FutureTask<Object>(new Callable<Object>() {
054            public Object call() throws Exception {
055                doPostCommit();
056                return null;
057            }   
058        });
059        
060        public byte getState() {
061            return state;
062        }
063    
064        public void setState(byte state) {
065            this.state = state;
066        }
067    
068        public boolean isCommitted() {
069            return committed;
070        }
071    
072        public void setCommitted(boolean committed) {
073            this.committed = committed;
074        }
075    
076        public void addSynchronization(Synchronization r) {
077            synchronizations.add(r);
078            if (state == START_STATE) {
079                state = IN_USE_STATE;
080            }
081        }
082    
083        public Synchronization findMatching(Synchronization r) {
084            int existing = synchronizations.indexOf(r);
085            if (existing != -1) {
086                return synchronizations.get(existing);
087            }
088            return null;
089        }
090    
091        public void removeSynchronization(Synchronization r) {
092            synchronizations.remove(r);
093        }
094    
095        public void prePrepare() throws Exception {
096    
097            // Is it ok to call prepare now given the state of the
098            // transaction?
099            switch (state) {
100            case START_STATE:
101            case IN_USE_STATE:
102                break;
103            default:
104                XAException xae = new XAException("Prepare cannot be called now.");
105                xae.errorCode = XAException.XAER_PROTO;
106                throw xae;
107            }
108    
109            // // Run the prePrepareTasks
110            // for (Iterator iter = prePrepareTasks.iterator(); iter.hasNext();) {
111            // Callback r = (Callback) iter.next();
112            // r.execute();
113            // }
114        }
115        
116        protected void fireBeforeCommit() throws Exception {
117            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
118                Synchronization s = iter.next();
119                s.beforeCommit();
120            }
121        }
122    
123        protected void fireAfterCommit() throws Exception {
124            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
125                Synchronization s = iter.next();
126                s.afterCommit();
127            }
128        }
129    
130        public void fireAfterRollback() throws Exception {
131            Collections.reverse(synchronizations);
132            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
133                Synchronization s = iter.next();
134                s.afterRollback();
135            }
136        }
137    
138        @Override
139        public String toString() {
140            return "Local-" + getTransactionId() + "[synchronizations=" + synchronizations + "]";
141        }
142    
143        public abstract void commit(boolean onePhase) throws XAException, IOException;
144    
145        public abstract void rollback() throws XAException, IOException;
146    
147        public abstract int prepare() throws XAException, IOException;
148    
149        public abstract TransactionId getTransactionId();
150    
151        public abstract Logger getLog();
152        
153        public boolean isPrepared() {
154            return getState() == PREPARED_STATE;
155        }
156        
157        public int size() {
158            return synchronizations.size();
159        }
160        
161        protected void waitPostCommitDone(FutureTask<?> postCommitTask) throws XAException, IOException {
162            try {
163                postCommitTask.get();
164            } catch (InterruptedException e) {
165                throw new InterruptedIOException(e.toString());
166            } catch (ExecutionException e) {
167                Throwable t = e.getCause();
168                if (t instanceof XAException) {
169                    throw (XAException) t;
170                } else if (t instanceof IOException) {
171                    throw (IOException) t;
172                } else {
173                    throw new XAException(e.toString());
174                }
175            }    
176        }
177        
178        protected void doPreCommit() throws XAException {
179            try {
180                fireBeforeCommit();
181            } catch (Throwable e) {
182                // I guess this could happen. Post commit task failed
183                // to execute properly.
184                getLog().warn("PRE COMMIT FAILED: ", e);
185                XAException xae = new XAException("PRE COMMIT FAILED");
186                xae.errorCode = XAException.XAER_RMERR;
187                xae.initCause(e);
188                throw xae;
189            }
190        }
191    
192        protected void doPostCommit() throws XAException {
193            try {
194                setCommitted(true);
195                fireAfterCommit();
196            } catch (Throwable e) {
197                // I guess this could happen. Post commit task failed
198                // to execute properly.
199                getLog().warn("POST COMMIT FAILED: ", e);
200                XAException xae = new XAException("POST COMMIT FAILED");
201                xae.errorCode = XAException.XAER_RMERR;
202                xae.initCause(e);
203                throw xae;
204            }
205        }
206    }