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 */
017package org.apache.activemq.transaction;
018
019import java.io.IOException;
020import java.io.InterruptedIOException;
021import java.util.ArrayList;
022import java.util.Collections;
023import java.util.Iterator;
024import java.util.concurrent.Callable;
025import java.util.concurrent.ExecutionException;
026import java.util.concurrent.FutureTask;
027import javax.jms.TransactionRolledBackException;
028import javax.transaction.xa.XAException;
029
030import org.apache.activemq.TransactionContext;
031import org.apache.activemq.command.TransactionId;
032import org.slf4j.Logger;
033
034/**
035 * Keeps track of all the actions the need to be done when a transaction does a
036 * commit or rollback.
037 * 
038 * 
039 */
040public abstract class Transaction {
041
042    public static final byte START_STATE = 0; // can go to: 1,2,3
043    public static final byte IN_USE_STATE = 1; // can go to: 2,3
044    public static final byte PREPARED_STATE = 2; // can go to: 3
045    public static final byte FINISHED_STATE = 3;
046    boolean committed = false;
047    Throwable rollackOnlyCause = null;
048
049    private final ArrayList<Synchronization> synchronizations = new ArrayList<Synchronization>();
050    private byte state = START_STATE;
051    protected FutureTask<?> preCommitTask = new FutureTask<Object>(new Callable<Object>() {
052        public Object call() throws Exception {
053            doPreCommit();
054            return null;
055        }
056    });
057    protected FutureTask<?> postCommitTask = new FutureTask<Object>(new Callable<Object>() {
058        public Object call() throws Exception {
059            doPostCommit();
060            return null;
061        }
062    });
063
064    public byte getState() {
065        return state;
066    }
067
068    public void setState(byte state) {
069        this.state = state;
070    }
071
072    public boolean isCommitted() {
073        return committed;
074    }
075
076    public void setCommitted(boolean committed) {
077        this.committed = committed;
078    }
079
080    public void addSynchronization(Synchronization r) {
081        synchronized (synchronizations) {
082            synchronizations.add(r);
083        }
084        if (state == START_STATE) {
085            state = IN_USE_STATE;
086        }
087    }
088
089    public Synchronization findMatching(Synchronization r) {
090        synchronized(synchronizations) {
091            int existing = synchronizations.indexOf(r);
092            if (existing != -1) {
093                return synchronizations.get(existing);
094            }
095        }
096        return null;
097    }
098
099    public void removeSynchronization(Synchronization r) {
100        synchronized(synchronizations) {
101            synchronizations.remove(r);
102        }
103    }
104
105    public void prePrepare() throws Exception {
106
107        // Is it ok to call prepare now given the state of the
108        // transaction?
109        switch (state) {
110        case START_STATE:
111        case IN_USE_STATE:
112            break;
113        default:
114            XAException xae = newXAException("Prepare cannot be called now", XAException.XAER_PROTO);
115            throw xae;
116        }
117
118        if (isRollbackOnly()) {
119            XAException xae = newXAException("COMMIT FAILED: Transaction marked rollback only", XAException.XA_RBROLLBACK);
120            TransactionRolledBackException transactionRolledBackException = new TransactionRolledBackException(xae.getLocalizedMessage());
121            transactionRolledBackException.initCause(rollackOnlyCause);
122            xae.initCause(transactionRolledBackException);
123            throw xae;
124        }
125    }
126
127    protected void fireBeforeCommit() throws Exception {
128        synchronized(synchronizations) {
129            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
130                Synchronization s = iter.next();
131                s.beforeCommit();
132            }
133        }
134    }
135
136    protected void fireAfterCommit() throws Exception {
137        synchronized(synchronizations) {
138            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
139                Synchronization s = iter.next();
140                s.afterCommit();
141            }
142        }
143    }
144
145    public void fireAfterRollback() throws Exception {
146        synchronized(synchronizations) {
147            Collections.reverse(synchronizations);
148            for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
149                Synchronization s = iter.next();
150               s.afterRollback();
151            }
152        }
153    }
154
155    @Override
156    public String toString() {
157        return "Local-" + getTransactionId() + "[synchronizations=" + synchronizations + "]";
158    }
159
160    public abstract void commit(boolean onePhase) throws XAException, IOException;
161
162    public abstract void rollback() throws XAException, IOException;
163
164    public abstract int prepare() throws XAException, IOException;
165
166    public abstract TransactionId getTransactionId();
167
168    public abstract Logger getLog();
169
170    public boolean isPrepared() {
171        return getState() == PREPARED_STATE;
172    }
173
174    public int size() {
175        return synchronizations.size();
176    }
177
178    protected void waitPostCommitDone(FutureTask<?> postCommitTask) throws XAException, IOException {
179        try {
180            postCommitTask.get();
181        } catch (InterruptedException e) {
182            throw new InterruptedIOException(e.toString());
183        } catch (ExecutionException e) {
184            Throwable t = e.getCause();
185            if (t instanceof XAException) {
186                throw (XAException) t;
187            } else if (t instanceof IOException) {
188                throw (IOException) t;
189            } else {
190                throw new XAException(e.toString());
191            }
192        }
193    }
194
195    protected void doPreCommit() throws XAException {
196        try {
197            fireBeforeCommit();
198        } catch (Throwable e) {
199            // I guess this could happen. Post commit task failed
200            // to execute properly.
201            getLog().warn("PRE COMMIT FAILED: ", e);
202            XAException xae = newXAException("PRE COMMIT FAILED", XAException.XAER_RMERR);
203            xae.initCause(e);
204            throw xae;
205        }
206    }
207
208    protected void doPostCommit() throws XAException {
209        try {
210            setCommitted(true);
211            fireAfterCommit();
212        } catch (Throwable e) {
213            // I guess this could happen. Post commit task failed
214            // to execute properly.
215            getLog().warn("POST COMMIT FAILED: ", e);
216            XAException xae = newXAException("POST COMMIT FAILED",  XAException.XAER_RMERR);
217            xae.initCause(e);
218            throw xae;
219        }
220    }
221
222    public static XAException newXAException(String s, int errorCode) {
223        XAException xaException = new XAException(s + " " + TransactionContext.xaErrorCodeMarker + errorCode);
224        xaException.errorCode = errorCode;
225        return xaException;
226    }
227
228    public void setRollbackOnly(Throwable cause) {
229        if (!isRollbackOnly()) {
230            getLog().trace("setting rollback only, cause:", cause);
231            rollackOnlyCause = cause;
232        }
233    }
234
235    public boolean isRollbackOnly() {
236        return rollackOnlyCause != null;
237    }
238
239}