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        int existing = synchronizations.indexOf(r);
091        if (existing != -1) {
092            return synchronizations.get(existing);
093        }
094        return null;
095    }
096
097    public void removeSynchronization(Synchronization r) {
098        synchronizations.remove(r);
099    }
100
101    public void prePrepare() throws Exception {
102
103        // Is it ok to call prepare now given the state of the
104        // transaction?
105        switch (state) {
106        case START_STATE:
107        case IN_USE_STATE:
108            break;
109        default:
110            XAException xae = newXAException("Prepare cannot be called now", XAException.XAER_PROTO);
111            throw xae;
112        }
113
114        if (isRollbackOnly()) {
115            XAException xae = newXAException("COMMIT FAILED: Transaction marked rollback only", XAException.XA_RBROLLBACK);
116            TransactionRolledBackException transactionRolledBackException = new TransactionRolledBackException(xae.getLocalizedMessage());
117            transactionRolledBackException.initCause(rollackOnlyCause);
118            xae.initCause(transactionRolledBackException);
119            throw xae;
120        }
121    }
122    
123    protected void fireBeforeCommit() throws Exception {
124        for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
125            Synchronization s = iter.next();
126            s.beforeCommit();
127        }
128    }
129
130    protected void fireAfterCommit() throws Exception {
131        for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
132            Synchronization s = iter.next();
133            s.afterCommit();
134        }
135    }
136
137    public void fireAfterRollback() throws Exception {
138        Collections.reverse(synchronizations);
139        for (Iterator<Synchronization> iter = synchronizations.iterator(); iter.hasNext();) {
140            Synchronization s = iter.next();
141            s.afterRollback();
142        }
143    }
144
145    @Override
146    public String toString() {
147        return "Local-" + getTransactionId() + "[synchronizations=" + synchronizations + "]";
148    }
149
150    public abstract void commit(boolean onePhase) throws XAException, IOException;
151
152    public abstract void rollback() throws XAException, IOException;
153
154    public abstract int prepare() throws XAException, IOException;
155
156    public abstract TransactionId getTransactionId();
157
158    public abstract Logger getLog();
159    
160    public boolean isPrepared() {
161        return getState() == PREPARED_STATE;
162    }
163    
164    public int size() {
165        return synchronizations.size();
166    }
167    
168    protected void waitPostCommitDone(FutureTask<?> postCommitTask) throws XAException, IOException {
169        try {
170            postCommitTask.get();
171        } catch (InterruptedException e) {
172            throw new InterruptedIOException(e.toString());
173        } catch (ExecutionException e) {
174            Throwable t = e.getCause();
175            if (t instanceof XAException) {
176                throw (XAException) t;
177            } else if (t instanceof IOException) {
178                throw (IOException) t;
179            } else {
180                throw new XAException(e.toString());
181            }
182        }    
183    }
184    
185    protected void doPreCommit() throws XAException {
186        try {
187            fireBeforeCommit();
188        } catch (Throwable e) {
189            // I guess this could happen. Post commit task failed
190            // to execute properly.
191            getLog().warn("PRE COMMIT FAILED: ", e);
192            XAException xae = newXAException("PRE COMMIT FAILED", XAException.XAER_RMERR);
193            xae.initCause(e);
194            throw xae;
195        }
196    }
197
198    protected void doPostCommit() throws XAException {
199        try {
200            setCommitted(true);
201            fireAfterCommit();
202        } catch (Throwable e) {
203            // I guess this could happen. Post commit task failed
204            // to execute properly.
205            getLog().warn("POST COMMIT FAILED: ", e);
206            XAException xae = newXAException("POST COMMIT FAILED",  XAException.XAER_RMERR);
207            xae.initCause(e);
208            throw xae;
209        }
210    }
211
212    public static XAException newXAException(String s, int errorCode) {
213        XAException xaException = new XAException(s + " " + TransactionContext.xaErrorCodeMarker + errorCode);
214        xaException.errorCode = errorCode;
215        return xaException;
216    }
217
218    public void setRollbackOnly(Throwable cause) {
219        if (!isRollbackOnly()) {
220            getLog().trace("setting rollback only, cause:", cause);
221            rollackOnlyCause = cause;
222        }
223    }
224
225    public boolean isRollbackOnly() {
226        return rollackOnlyCause != null;
227    }
228
229}