001/*
002 * HA-JDBC: High-Availability JDBC
003 * Copyright (C) 2012  Paul Ferraro
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Lesser General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package net.sf.hajdbc.tx;
019
020import java.nio.ByteBuffer;
021import java.util.UUID;
022
023/**
024 * Transaction identifier factory that generates random UUIDs.
025 * This implementation is safe for <distributable/> clusters.
026 * @author Paul Ferraro
027 */
028public class UUIDTransactionIdentifierFactory implements TransactionIdentifierFactory<UUID>
029{
030        /**
031         * {@inheritDoc}
032         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#createTransactionIdentifier()
033         */
034        @Override
035        public UUID createTransactionIdentifier()
036        {
037                return UUID.randomUUID();
038        }
039
040        /**
041         * {@inheritDoc}
042         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#serialize(java.lang.Object)
043         */
044        @Override
045        public byte[] serialize(UUID transactionId)
046        {
047                return ByteBuffer.allocate(this.size()).putLong(transactionId.getMostSignificantBits()).putLong(transactionId.getLeastSignificantBits()).array();
048        }
049
050        /**
051         * {@inheritDoc}
052         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#deserialize(byte[])
053         */
054        @Override
055        public UUID deserialize(byte[] bytes)
056        {
057                ByteBuffer buffer = ByteBuffer.wrap(bytes);
058                return new UUID(buffer.getLong(), buffer.getLong());
059        }
060
061        /**
062         * {@inheritDoc}
063         * @see net.sf.hajdbc.tx.TransactionIdentifierFactory#size()
064         */
065        @Override
066        public int size()
067        {
068                return Long.SIZE * 2;
069        }
070}