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