package com.lightstreamer.req_resp_examples.fake_sub;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.lightstreamer.interfaces.data.DataProvider;
import com.lightstreamer.interfaces.data.DataProviderException;
import com.lightstreamer.interfaces.data.FailureException;
import com.lightstreamer.interfaces.data.ItemEventListener;
import com.lightstreamer.interfaces.data.SubscriptionException;
public class FakeSubAdapter implements DataProvider {
private ItemEventListener listener;
public void init
(Map params,
File configDir
) throws DataProviderException
{
return;
}
public void setListener(ItemEventListener listener) {
//set the listener that will receive the updates
this.listener = listener;
}
public void subscribe
(String itemName,
boolean needsIterator
) throws SubscriptionException, FailureException
{
//create the thread that will handle the response. In a production
//scenario you would probably use a pool, but for this example
//create a new thread per each subscription is enough
ResponseThread rt = new ResponseThread(itemName);
//take trace of each subscribtion-related thread
responseThreads.put(itemName,rt);
//starts the thread that will send the response to clients
rt.start();
}
public void unsubscribe
(String itemName
) throws SubscriptionException, FailureException
{
ResponseThread rt = (ResponseThread) responseThreads.get(itemName);
if (rt != null) {
//remove from subscription-related threads list
responseThreads.remove(itemName);
//if the thread is sending something (ie it has not finished to send the snapshot
//that is our response) we stop it
rt.end();
}
}
public boolean isSnapshotAvailable
(String itemName
) throws SubscriptionException
{
//in this case we send ONLY the snapshot, so it is obviously always available
return true;
}
public class ResponseThread
extends Thread {
private volatile boolean exit = false;
public ResponseThread
(String itemName
) {
//save the itemName, we will use this name as part of the
//updates
this.itemName = itemName;
}
public void run() {
//the response will be a DISTINCT table with 5 rows
for(int i=1; i<=5 && !this.exit; i++) {
//compose a Map to be passed to Lightstreamer kernel
row.
put("key",
this.
itemName + "->" +String.
valueOf(i
));
row.put("value","Value"+i);
//pass the map to Lightstreamer kernel. This is an update.
if (!this.exit)listener.update(this.itemName,row,true);
}
//send the endOfSnapshot signal (ie response is finished)
if (!this.exit)listener.endOfSnapshot(this.itemName);
}
public void end() {
//set a flag to stop updates
this.exit = true;
}
}
}
Bookmarks