com.butor.notif.AbstractNotifSession Maven / Gradle / Ivy
/**
* Copyright 2013-2019 Butor Inc.
*
* 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 com.butor.notif;
import java.util.Date;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import org.butor.json.JsonHelper;
import org.butor.utils.CommonDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
public abstract class AbstractNotifSession implements NotifSession {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private boolean active = true;
private Queue queue = new LinkedBlockingQueue();
private Object mutex;
private String id = null;
private JsonHelper jsh = new JsonHelper();
private long time = 0;
private long prevTime = 0;
private NotifManager notifManager;
private String username = null;
private Map subscription = Maps.newConcurrentMap();
private int keepAliveIntervalMS = 15000;
public AbstractNotifSession(String id, String username) {
this.id = Preconditions.checkNotNull(id);
this.username = Preconditions.checkNotNull(username);
}
public void setKeepAliveIntervalMS(int keepAliveIntervalMS) {
Math.max(keepAliveIntervalMS, this.keepAliveIntervalMS);
}
public String getId() {
return id;
}
public void add(Notification notif, String serializedNotif) {
if (!active || mutex == null) {
return;
}
if (subscription.containsKey(notif.getType())) {
queue.add(serializedNotif);
synchronized (mutex) {
mutex.notifyAll();
}
}
}
public boolean isEmpty() {
return queue.isEmpty();
}
public void shutdown() {
active = false;
queue.clear();
if (mutex!=null) {
synchronized (mutex) {
mutex.notifyAll();
}
mutex = null;
}
logger.info("shutdown done.");
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Object getMutex() {
return mutex;
}
public void setMutex(Object mutex) {
if (this.mutex != null) {
synchronized (this.mutex) {
this.mutex.notifyAll();
}
}
this.mutex = mutex;
}
public void handleClientMessage(String serializedMessage) {
try {
OutboundNotif notif = jsh.deserialize(serializedMessage, OutboundNotif.class);
notif.getData().put("username", username);
notif.getData().put("sessionId", id);
notif.getData().put("time", CommonDateFormat.YYYYMMDD_HHMMSS.format(new Date()));
if (notif.getType().equalsIgnoreCase("subscribe")) {
String username = (String)notif.getData().get("username");
logger.info("Got subscription {} from user {}", notif.getName(), username);
subscription.put(notif.getName(), "");
} else if (notif.getType().equalsIgnoreCase("unsubscribe")) {
String username = (String)notif.getData().get("username");
logger.info("Got unsubscription {} from user {}", notif.getName(), username);
subscription.remove(notif.getName());
}
notifManager.handleClientNotif(notif);
} catch (Exception e) {
logger.warn("failed while handling client message! " +serializedMessage);
}
}
public boolean post() {
String msg = queue.poll();
if (msg == null) {
time = System.currentTimeMillis();
if (time -prevTime > keepAliveIntervalMS) {
prevTime = time;
msg = "keep-alive";
}
}
if (msg != null) {
try {
prevTime = time;
sendToClient(msg);
} catch (Exception e) {
logger.warn("Failed while sending message to client!", e);
}
}
return queue.size() > 0;
}
protected abstract void sendToClient(String serializedMessage);
public void setNotifManager(NotifManager notifManager) {
this.notifManager = Preconditions.checkNotNull(notifManager);
}
public String getUsername() {
return username;
}
}