001// SPDX-License-Identifier: GPL-3.0-or-later
002
003package es.uvigo.esei.sing.textproc.persistence;
004
005import java.util.concurrent.atomic.AtomicLong;
006
007import javax.persistence.EntityTransaction;
008
009import lombok.Getter;
010import lombok.NonNull;
011
012/**
013 * Encapsulates a entity transaction with its creation time. Objects of this
014 * class can be sorted by the entity transaction creation order. However,
015 * two timestamped entity transactions are equal if and only if their underlying
016 * entity transaction are equal.
017 *
018 * @author Alejandro González García
019 */
020final class TimestampedEntityTransaction implements Comparable<TimestampedEntityTransaction> {
021        private static final AtomicLong NEXT_CREATION_ID = new AtomicLong();
022
023        @Getter
024        private final EntityTransaction entityTransaction;
025        private final long creationId;
026
027        /**
028         * Encapsulates the given entity transaction in a timestamped entity
029         * transaction.
030         *
031         * @param entityTransaction The entity transaction to encapsulate.
032         * @throws IllegalArgumentException If {@code entityTransaction} is {@code null}.
033         */
034        public TimestampedEntityTransaction(@NonNull final EntityTransaction entityTransaction) {
035                this.entityTransaction = entityTransaction;
036                this.creationId = NEXT_CREATION_ID.getAndIncrement();
037        }
038
039        @Override
040        public int compareTo(final TimestampedEntityTransaction o) {
041                return (int) Math.max(Math.min(Integer.MIN_VALUE, creationId - o.creationId), Integer.MAX_VALUE);
042        }
043
044        @Override
045        public boolean equals(final Object other) {
046                return other instanceof TimestampedEntityTransaction &&
047                        ((TimestampedEntityTransaction) other).entityTransaction.equals(entityTransaction);
048        }
049
050        @Override
051        public int hashCode() {
052                return entityTransaction.hashCode();
053        }
054}