001/*
002 * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bdelbosc
018 */
019package org.nuxeo.ecm.platform.importer.mqueues.mqueues.internals;
020
021import org.nuxeo.ecm.platform.importer.mqueues.mqueues.MQOffset;
022import org.nuxeo.ecm.platform.importer.mqueues.mqueues.MQPartition;
023
024/**
025 * @since 9.1
026 */
027public class MQOffsetImpl implements MQOffset {
028    protected MQPartition partition;
029    protected final long offset;
030
031    public MQOffsetImpl(MQPartition partition, long offset) {
032        this.partition = partition;
033        this.offset = offset;
034    }
035
036    public MQOffsetImpl(String name, int partition, long offset) {
037        this.partition = MQPartition.of(name, partition);
038        this.offset = offset;
039    }
040
041    @Override
042    public MQPartition partition() {
043        return partition;
044    }
045
046    @Override
047    public long offset() {
048        return offset;
049    }
050
051    @Override
052    public String toString() {
053        return String.format("%s:+%d", partition, offset);
054    }
055
056    @Override
057    public boolean equals(Object o) {
058        if (this == o) return true;
059        if (o == null || getClass() != o.getClass()) return false;
060
061        MQOffsetImpl offsetImpl = (MQOffsetImpl) o;
062
063        if (partition.equals(offsetImpl.partition)) return false;
064        return offset == offsetImpl.offset;
065    }
066
067    @Override
068    public int hashCode() {
069        int result = partition != null ? partition.hashCode() : 0;
070        result = 31 * result + (int) (offset ^ (offset >>> 32));
071        return result;
072    }
073
074    @Override
075    public int compareTo(MQOffset o) {
076        if (this == o) return 0;
077        if (o == null || getClass() != o.getClass()) {
078            throw new IllegalArgumentException("Can not compare offsets with different classes");
079        }
080        MQOffsetImpl offsetImpl = (MQOffsetImpl) o;
081        if (partition.equals(offsetImpl.partition)) {
082            throw new IllegalArgumentException("Can not compare offsets from different partitions");
083        }
084        return (int) (offset - offsetImpl.offset);
085    }
086}