FirehoseDelayedEvent.java

/*
 * Copyright 2021 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gringlobal.component.firehose;

import java.time.Instant;
import java.util.Objects;

import org.gringlobal.component.firehose.FirehoseEvent.EventType;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * {@code FirehoseDelayedEvent} types are generated by the {@link FirehoseMessageProcessor}.
 * They are kept in a queue and only sent out after the configured delay time.
 */
@Getter
@Setter
@ToString
public class FirehoseDelayedEvent {

	private EventType eventType;
	private Instant timestamp;

	private Class<?> clazz;
	private Long id;
	private Object entity;

	/** SID that triggered the event */
	private Long sid;

	public FirehoseDelayedEvent(EventType eventType, FirehoseEvent event) {
		this.eventType = eventType == null ? event.getEventType() : event.getEventType();
		this.clazz = event.getClazz();
		this.id = event.getId();
		this.timestamp = event.getTimestamp();
		this.entity = event.getEntity();
		this.sid = event.getSid();
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (!(o instanceof FirehoseDelayedEvent)) return false;
		FirehoseDelayedEvent that = (FirehoseDelayedEvent) o;
		return Objects.equals(timestamp, that.timestamp) && Objects.equals(id, that.id) && Objects.equals(clazz, that.clazz);
	}

	@Override
	public int hashCode() {
		return Objects.hash(timestamp, clazz, id);
	}

	/**
	 * Compare by timestamp, then id, then clazz
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static int compareTo(FirehoseDelayedEvent a, FirehoseDelayedEvent b) {
		if (a.timestamp.equals(b.timestamp)) {
			if (b.id == null && a.id == null) {
				return 0;
			} else if (b.id == null) {
				return -1;
			} else if (a.id == null) {
				return 1;
			} else {
				return (int) (a.id - b.id);
			}
		} else {
			return a.timestamp.compareTo(b.timestamp);
		}
	}

	/**
	 * Match by id and clazz
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public boolean sameReference(FirehoseDelayedEvent b) {
		if (b == null) {
			return false;
		}
		return Objects.equals(id, b.id) && Objects.equals(clazz, b.clazz);
	}
}