I modified the
HelloWorldDataAdapter to poll a database, instead of generating the data internally.
Please consider this is just a five-minute effort and I've not tried to compile the code. Please let me know if you find any errors.
This Data Adapter uses JDBC to query an Access file ("C:/Data.mdb"). Every second, it reads the first record, extracts the "message" and "timestamp" fields and injects them into the Lightstreamer Kernel.
[syntax=JAVA]import java.util.*;
import java.io.File;
import java.sql.*;
import com.lightstreamer.interfaces.data.*;
public class HelloWorldDataAdapter implements SmartDataProvider {
private ItemEventListener listener;
private volatile GreetingsThread gt;
private Statement command;
public void init(Map params, File configDir) throws DataProviderException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String dbFile = "C:/Data.mdb";
String database = "jdbc:odbc :Smile_Ag: river={Microsoft Access Driver (*.mdb)};DBQ="
+ dbFile.trim()+ ";DriverID=22;READONLY=true}";
Connection conn = DriverManager.getConnection(database, "", "");
command = conn.createStatement();
} catch (Exception ex) {
System.out.println(ex);
throw new DataProviderException(ex.getMessage());
}
}
public boolean isSnapshotAvailable(String itemName) throws SubscriptionException {
return false;
}
public void setListener(ItemEventListener listener) {
this.listener = listener;
}
public void subscribe(String itemName, Object itemHandle, boolean needsIterator)
throws SubscriptionException, FailureException {
if (itemName.equals("greetings")) {
gt = new GreetingsThread(itemHandle);
gt.start();
}
}
public void subscribe(String itemName, boolean needsIterator)
throws SubscriptionException, FailureException {
}
public void unsubscribe(String itemName) throws SubscriptionException,
FailureException {
if (itemName.equals("greetings") && gt != null) {
gt.go = false;
}
}
class GreetingsThread extends Thread {
private final Object itemHandle;
public volatile boolean go = true;
public GreetingsThread(Object itemHandle) {
this.itemHandle = itemHandle;
}
public void run() {
int c = 0;
Random rand = new Random();
while(go) {
try {
ResultSet rs = command.executeQuery("select * from Data");
if (rs.next()) {
Map<String, String> data = new HashMap<String, String>();
data.put("message", rs.getString("message"));
data.put("timestamp", rs.getString("timestamp"));
listener.smartUpdate(itemHandle, data, false);
}
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
}[/syntax]