001/* 
002 * JKNIV, whinstone one contract to access your database.
003 * 
004 * Copyright (C) 2017, the original author or authors.
005 *
006 * This library is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 2.1 of the License.
010 * 
011 * This library is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 * 
016 * You should have received a copy of the GNU Lesser General Public
017 * License along with this library; if not, write to the Free Software Foundation, Inc., 
018 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
019 */
020package net.sf.jkniv.whinstone.jpa2.transaction;
021
022import javax.persistence.EntityTransaction;
023
024import net.sf.jkniv.asserts.Assertable;
025import net.sf.jkniv.asserts.AssertsFactory;
026import net.sf.jkniv.sqlegance.transaction.TransactionType;
027import net.sf.jkniv.whinstone.transaction.TransactionStatus;
028import net.sf.jkniv.whinstone.transaction.Transactional;
029
030public class JpaTransactionAdapter implements Transactional
031{
032    private final static  Assertable notNull = AssertsFactory.getNotNull();
033    private final EntityTransaction tx;
034    private TransactionStatus status;
035    
036    /**
037     * Create transaction adapter for JPA Entity Transaction
038     * @param tx control transactions on resource-local entity managers
039     */
040    public JpaTransactionAdapter(EntityTransaction  tx)
041    {
042        notNull.verify(tx);
043        this.tx = tx;
044        this.status = (tx.isActive() ? TransactionStatus.ACTIVE : TransactionStatus.NO_TRANSACTION);
045    }
046
047    @Override
048    public TransactionType geTransactionType()
049    {
050        return TransactionType.LOCAL;
051    }
052
053    @Override
054    public TransactionStatus getStatus()
055    {
056        return status;
057    }
058
059    @Override
060    public void begin()
061    {
062        this.tx.begin();
063        this.status = TransactionStatus.ACTIVE;
064    }
065
066    @Override
067    public void commit()
068    {
069        this.tx.commit();
070        this.status = TransactionStatus.COMMITTED;
071    }
072
073    @Override
074    public void rollback()
075    {
076        this.tx.rollback();
077        this.status = TransactionStatus.ROLLEDBACK;
078    }
079    
080    @Override
081    public String toString()
082    {
083        return "JpaTransactionAdapter [EntityTransaction=" + tx + ", status=" +status+ "]";
084    }
085
086
087}