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