001/*
002 * Copyright 2011 Atteo.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014package org.atteo.moonshine.hibernate;
015
016import javax.inject.Inject;
017import javax.inject.Provider;
018import javax.transaction.Synchronization;
019import javax.transaction.SystemException;
020import javax.transaction.Transaction;
021import javax.transaction.TransactionManager;
022import javax.transaction.UserTransaction;
023
024import org.hibernate.service.jta.platform.internal.JtaSynchronizationStrategy;
025import org.hibernate.service.jta.platform.internal.TransactionManagerAccess;
026import org.hibernate.service.jta.platform.internal.TransactionManagerBasedSynchronizationStrategy;
027import org.hibernate.service.jta.platform.spi.JtaPlatform;
028
029@SuppressWarnings("serial")
030public class CustomJtaPlatform implements JtaPlatform {
031    @Inject
032    private Provider<TransactionManager> manager;
033
034    @Inject
035    private Provider<UserTransaction> userTransaction;
036
037    private final JtaSynchronizationStrategy synchronizationStrategy =
038            new TransactionManagerBasedSynchronizationStrategy(new TransactionManagerAccess() {
039        @Override
040        public TransactionManager getTransactionManager() {
041            return retrieveTransactionManager();
042        }
043    });
044
045    @Override
046    public TransactionManager retrieveTransactionManager() {
047        return manager.get();
048    }
049
050    @Override
051    public UserTransaction retrieveUserTransaction() {
052        return userTransaction.get();
053    }
054
055    @Override
056    public Object getTransactionIdentifier(Transaction transaction) {
057        return transaction;
058    }
059
060    @Override
061    public boolean canRegisterSynchronization() {
062        return synchronizationStrategy.canRegisterSynchronization();
063    }
064
065    @Override
066    public void registerSynchronization(Synchronization synchronization) {
067        synchronizationStrategy.registerSynchronization(synchronization);
068    }
069
070    @Override
071    public int getCurrentStatus() throws SystemException {
072        return manager.get().getStatus();
073    }
074}