I am trying to understand the concept of Strong and Causal consistency by implementing it in Multi-threaded Java. I have written the following code using the Vert.x framework. I am trying to implement the following:
Strong Consistency
Every PUT (write) request is atomic across all replicas.
At any point in time, only 1 PUT request per key can be performed on the datacenter instances.
A GET operation per key is to be blocked if a PUT operation for the same key is being processed.
The locking of datacenters is to be done at key level i.e. operations on multiple keys can run in parallel.
Causal Consistency
ALL PUT operations per key must be seen in all the datacenters in the same order.
At any point in time, different operations can be performed in different datacenters in parallel. That is, lock only one datacenter at a time for an operation per key.
A GET operation returns the value immediately without being blocked even if it is stale.
API on the Vert.x server
Here are the following GET and PUT operations that the Vert.x server will receive and must implement:
Vertx-DNS:8080/put?key=KEY&value=VALUE
This endpoint will receive the key, value pair that needs to be stored in the datacenter instances
Vertx-DNS:8080/get?key=KEY&loc=LOCATION
This endpoint will receive the key for which the value has to be returned by the Vertx server. The server has to return the value as the response to this request. The location value is 1 for datacenter1, 2 for datacenter2 and 3 datacenter3.
KeyValueLib.PUT(String datacenterDNS, String key, String value) throws IOException
This API method will put the value for the specified key in the specified datacenter instance.
KeyValueLib.GET(String datacenterDNS, String key) throws IOException
This API method returns the value for the specified key from the specified datacenter.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.TimeZone;
import java.util.Iterator;
import java.util.Collections;
import java.util.List;
import java.sql.Timestamp;
import org.vertx.java.core.Handler;
import org.vertx.java.core.MultiMap;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.platform.Verticle;
public class Coordinator extends Verticle {
//Default mode: Strongly consistent. Possible values are "strong" and "causal"
private static String consistencyType = "strong";
/**
* TODO: Set the values of the following variables to the DNS names of your
* three dataCenter instances
*/
private static final String dataCenter1 = "ec2-52-2-18-9.compute-1.amazonaws.com";
private static final String dataCenter2 = "ec2-52-2-12-29.compute-1.amazonaws.com";
private static final String dataCenter3 = "ec2-52-2-10-12.compute-1.amazonaws.com";
#Override
public void start() {
//DO NOT MODIFY THIS
KeyValueLib.dataCenters.put(dataCenter1, 1);
KeyValueLib.dataCenters.put(dataCenter2, 2);
KeyValueLib.dataCenters.put(dataCenter3, 3);
final RouteMatcher routeMatcher = new RouteMatcher();
final HttpServer server = vertx.createHttpServer();
server.setAcceptBacklog(32767);
server.setUsePooledBuffers(true);
server.setReceiveBufferSize(4 * 1024);
routeMatcher.get("/put", new Handler<HttpServerRequest>() {
#Override
public void handle(final HttpServerRequest req) {
MultiMap map = req.params();
final String key = map.get("key");
final String value = map.get("value");
//You may use the following timestamp for ordering requests
final String timestamp = new Timestamp(System.currentTimeMillis()
+ TimeZone.getTimeZone("EST").getRawOffset()).toString();
Thread t = new Thread(new Runnable() {
public void run() {
//TODO: Write code for PUT operation here.
//Each PUT operation is handled in a different thread.
//Use helper functions.
try{
switch(consistencyType) {
case "strong":
//Do
break;
case "causal":
//Do
break;
default: continue;
}
}
}
});
t.start();
req.response().end(); //Do not remove this
}
});
routeMatcher.get("/get", new Handler<HttpServerRequest>() {
#Override
public void handle(final HttpServerRequest req) {
MultiMap map = req.params();
final String key = map.get("key");
final String loc = map.get("loc");
//You may use the following timestamp for ordering requests
final String timestamp = new Timestamp(System.currentTimeMillis()
+ TimeZone.getTimeZone("EST").getRawOffset()).toString();
Thread t = new Thread(new Runnable() {
public void run() {
//TODO: Write code for GET operation here.
//Each GET operation is handled in a different thread.
//Highly recommended that you make use of helper functions.
req.response().end("0"); //Default response = 0
}
});
t.start();
}
});
routeMatcher.get("/consistency", new Handler<HttpServerRequest>() {
#Override
public void handle(final HttpServerRequest req) {
MultiMap map = req.params();
consistencyType = map.get("consistency");
req.response().end();
}
});
routeMatcher.noMatch(new Handler<HttpServerRequest>() {
#Override
public void handle(final HttpServerRequest req) {
req.response().putHeader("Content-Type", "text/html");
String response = "Not found.";
req.response().putHeader("Content-Length",
String.valueOf(response.length()));
req.response().end(response);
req.response().close();
}
});
server.requestHandler(routeMatcher);
server.listen(8001);
}
}
KeyValueLib.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
public class KeyValueLib {
public static HashMap<String, Integer> dataCenters = new HashMap();
private static String URLHandler(String string) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try {
String string2;
URL uRL = new URL(string);
HttpURLConnection httpURLConnection = (HttpURLConnection) uRL
.openConnection();
if (httpURLConnection.getResponseCode() != 200) {
throw new IOException(httpURLConnection.getResponseMessage());
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()));
while ((string2 = bufferedReader.readLine()) != null) {
stringBuilder.append(string2);
}
bufferedReader.close();
httpURLConnection.disconnect();
} catch (MalformedURLException var2_3) {
var2_3.printStackTrace();
}
return stringBuilder.toString();
}
public static void PUT(String string, String string2, String string3)
throws IOException {
String string4 = String.format("http://%s:8001/put?key=%s&value=%s",
string, string2, string3);
String string5 = KeyValueLib.URLHandler(string4);
try {
switch (dataCenters.get(string)) {
case 1 : {
break;
}
case 2 : {
Thread.sleep(200);
break;
}
case 3 : {
Thread.sleep(800);
break;
}
}
} catch (InterruptedException var5_5) {
// empty catch block
}
if (!string5.equals("stored")) {
System.out.println("Some error happened");
}
}
public static String GET(String string, String string2) throws IOException {
String string3 = String.format("http://%s:8001/get?key=%s", string,
string2);
String string4 = KeyValueLib.URLHandler(string3);
return string4;
}
}
Can someone help me how to implement this?
Related
My app is a game that is a simple words puzzle, so the levels on it is fetched from a Json web service, using AsyncTask class I can fetch the data in doInBackground and onPostExecute methods, I use local variables in FetchData class to hold the fetched data in, the data is simply 6 strings that are an image URL and level id, and 4 words that is for the buttons, here is the game interface, as you can see there are 4 buttons each one has a word and the player must find it by looking at the picture.
So when the player finds for example 1 word and leaves the app and closes it, the word the player found must be saved and when he return back to LevelActivity he is supposed to continue the level by finding more 3 words.
THE PROBLEM: is that when I find a word and the word shows (so it must be saved) when I close the app and return this happens, depending on my testing I found out that those lines of code that effects the data lag
NOTE: That whenever I reload the activity (manually) everything gets good and instead of having an empty button after recreating the activity the word shows.
data fetching method used: in onCreate & onResume
//This is in LevelActivity.java:
//These methods checks if the button is answered previously or not (button1/button2... variables are true when a word is answered)
public void checkButton1() {
if (button1) {
wordButton1.setText(button1Word); //<--- Here if I changed it to .setText("Test")
//the lag will disappear and the button will show "Test" (without the quotation) and everything's good
//So the problem is when I use .setText(button1Word); that is the word fetched from Json web service.
//it doesn't throw NullPointerException and it doesn't show the word
//but what? it set the text to " "? Why?
//Note other buttons are the same thing too
}
}
public void checkButton2() {
if (button2) {
wordButton2.setText(button2Word);
}
}
public void checkButton3() {
if (button3) {
wordButton3.setText(button3Word);
}
}
public void checkButton4() {
if (button4) {
wordButton4.setText(button4Word);
}
}
//This is FetchData class that fetches the data from Json web service (full code)
package com.example.wordspuzzlejsontest;
import android.content.Context;
import android.os.AsyncTask;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class FetchData extends AsyncTask<Void, Void, Void> {
//Local variable that are used to hold fetched data to transfer them to LevelActivity with static variables
static int currentLevel = 0;
String w1;
String w2;
String w3;
String w4;
String data = "";
String id;
String img;
Context context;
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.jsonbin.io/b/5e42776dd18e4016617690ce/7");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
JSONObject JO = (JSONObject) JA.get(currentLevel);
id = (String) JO.get("id");
img = (String) JO.get("img");
w1 = (String) JO.get("w1");
w2 = (String) JO.get("w2");
w3 = (String) JO.get("w3");
w4 = (String) JO.get("w4");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
int levelId = Integer.parseInt(id);
levelId++;
//Loading the words data to buttons
LevelActivity.levelID = String.valueOf(levelId);
LevelActivity.imageURL = img;
LevelActivity.button1Word = w1;
LevelActivity.button2Word = w2;
LevelActivity.button3Word = w3;
LevelActivity.button4Word = w4;
//Loading level image and level number on the screen
LevelActivity.levelIdTextView.setText(LevelActivity.levelID);
loadLevelImage();
}
public void loadLevelImage() {
Picasso.with(context).load(LevelActivity.imageURL).placeholder(R.drawable.loading)
.error(R.drawable.loading)
.into(LevelActivity.imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
}
});
}
}
Thanks for viewing my answer :D tell me if you need any other code.
At the end of onPostExecute() calls to
checkButton1()
checkButton2()
checkButton3()
checkButton4()
are missing. Because of that, buttons cannot know about the new values and therefore remain empty.
This is a mobile app composed in Java with Codename One's CODAPPS plugin for NetBeans IDE.
The code is from a Coursera course where a Twitter-clone app was developed. In the course the coding of the app was show, but the end result -- a wall of "Roars" (Tweets) which appears when you click Refresh -- was not shown, and does not appear to work.
There are no errors, but I simply cannot get it to display any Roars (Tweets). These are downloaded as JSON data. I confirmed that the data uploads and downloads as it should; it's just not displaying.
All of the user-written code is stored in a file called StateMachine.java. I will paste this code below. The entire project is also available here on GitHub.
/**
* Your application code goes here
*/
package userclasses;
import com.codename1.analytics.AnalyticsService;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.NetworkManager;
import com.codename1.io.Preferences;
import com.codename1.io.Util;
import com.codename1.processing.Result;
import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.Layout;
import com.codename1.ui.util.Resources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* #author Your name here
*/
public class StateMachine extends StateMachineBase {
String roar;
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class members there,
// the constructor might be invoked too late due to race conditions that might occur
}
/**
* this method should be used to initialize variables instead of the
* constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
AnalyticsService.init("UA-67803686-1", "irrelevant");
AnalyticsService.setAppsMode(true);
}
#Override
protected void onMain_ButtonAction(Component c, ActionEvent event) {
Hashtable infoToBeSent = new Hashtable();
infoToBeSent.put("roar", roar);
infoToBeSent.put("author", "seinecle");
final String infoInString = Result.fromContent(infoToBeSent).toString();
String firebase = "https://roar.firebaseIO.com/listofroars.json";
ConnectionRequest request = new ConnectionRequest() {
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(infoInString.getBytes("UTF-8"));
}
};
request.setUrl(firebase);
request.setPost(true);
request.setHttpMethod("POST");
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
}
#Override
protected void onMain_TextAreaAction(Component c, ActionEvent event) {
roar = findTextArea().getText();
if (roar == null) {
roar = "we did not get a roar from you";
}
}
#Override
protected void onWall_ButtonAction(Component c, ActionEvent event) {
try {
String roars = "https://roar.firebaseIO.com/listofroars.json";
//if we want to retrieve only the latest 10 roars posted
//String roars = "https://roar.firebaseIO.com/listofroars.json" + "?" + "orderBy=\"$key\"" + "&" + "limitToLast=10";
ConnectionRequest request = new ConnectionRequest();
request.setUrl(roars);
request.setPost(false);
request.setHttpMethod("GET");
request.setContentType("application/json");
NetworkManager.getInstance().addToQueueAndWait(request);
ByteArrayInputStream allRoarsInBytes = new ByteArrayInputStream(request.getResponseData());
String responseInString = Util.readToString(allRoarsInBytes, "UTF-8");
JSONObject allRoarsInJsonFormat = new JSONObject(responseInString);
JSONArray listOfRoarIds = allRoarsInJsonFormat.names();
Form wallScreen = c.getComponentForm();
Container myContainerForAllRoars = new Container();
Layout myLayout = new BoxLayout(BoxLayout.Y_AXIS);
myContainerForAllRoars.setLayout(myLayout);
Integer counterOfRoars = 0;
while (counterOfRoars < allRoarsInJsonFormat.length()) {
String idOfOneRoar = listOfRoarIds.getString(counterOfRoars);
JSONObject oneRoarInJsonFormat = (JSONObject) allRoarsInJsonFormat.get(idOfOneRoar);
Container myRoarContainer = new Container();
String author = oneRoarInJsonFormat.getString("author");
String roarText = oneRoarInJsonFormat.getString("roar");
Label myLabelForAuthor = new Label(author);
Label myLabelForRoar = new Label(roarText);
myRoarContainer.addComponent(myLabelForAuthor);
myRoarContainer.addComponent(myLabelForRoar);
myContainerForAllRoars.addComponent(myRoarContainer);
counterOfRoars = counterOfRoars + 1;
}
wallScreen.addComponent(wallScreen.getComponentCount(), myContainerForAllRoars);
wallScreen.revalidate();
} catch (IOException ex) {
} catch (JSONException ex) {
}
}
#Override
protected void onCreateUserName() {
String userName;
userName = Preferences.get("username", "");
if (userName != null) {
showForm("Main", null);
AnalyticsService.visit("Main", "UserName");
}
}
#Override
protected void onUserName_ButtonAction(Component c, ActionEvent event) {
String userName = findTextField().getText();
if (userName == null || userName.length() == 0) {
} else {
Preferences.set("username", userName);
showForm("Main", null);
AnalyticsService.visit("Main", "UserName");
}
}
}
I tried adding wallScreen.show() and Wall.show() but it didn't fix the problem.
Just add the following code and it works well on both connections
request.setDuplicateSupported(true);
I am using java spark API to write some test application . I am using a class which doesn't extends serializable interface . So to make the application work I am using kryo serializer to serialize the class . But the problem which I observed while debugging was that during the de-serialization the returned class object becomes null and in turn throws a null pointer exception . It seems to be closure problem where things are going wrong but not sure.Since I am new to this kind of serialization I don't know where to start digging.
Here is the code I am testing :
package org.apache.spark.examples;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
/**
* Spark application to test the Serialization issue in spark
*/
public class Test {
static PrintWriter outputFileWriter;
static FileWriter file;
static JavaSparkContext ssc;
public static void main(String[] args) {
String inputFile = "/home/incubator-spark/examples/src/main/scala/org/apache/spark/examples/InputFile.txt";
String master = "local";
String jobName = "TestSerialization";
String sparkHome = "/home/test/Spark_Installation/spark-0.7.0";
String sparkJar = "/home/test/TestSerializationIssesInSpark/TestSparkSerIssueApp/target/TestSparkSerIssueApp-0.0.1-SNAPSHOT.jar";
SparkConf conf = new SparkConf();
conf.set("spark.closure.serializer","org.apache.spark.serializer.KryoSerializer");
conf.set("spark.kryo.registrator", "org.apache.spark.examples.MyRegistrator");
// create the Spark context
if(master.equals("local")){
ssc = new JavaSparkContext("local", jobName,conf);
//ssc = new JavaSparkContext("local", jobName);
} else {
ssc = new JavaSparkContext(master, jobName, sparkHome, sparkJar);
}
JavaRDD<String> testData = ssc.textFile(inputFile).cache();
final NotSerializableJavaClass notSerializableTestObject= new NotSerializableJavaClass("Hi ");
#SuppressWarnings({ "serial", "unchecked"})
JavaRDD<String> classificationResults = testData.map(
new Function<String, String>() {
#Override
public String call(String inputRecord) throws Exception {
if(!inputRecord.isEmpty()) {
//String[] pointDimensions = inputRecord.split(",");
String result = "";
try {
FileWriter file = new FileWriter("/home/test/TestSerializationIssesInSpark/results/test_result_" + (int) (Math.random() * 100));
PrintWriter outputFile = new PrintWriter(file);
InetAddress ip;
ip = InetAddress.getLocalHost();
outputFile.println("IP of the server: " + ip);
result = notSerializableTestObject.testMethod(inputRecord);
outputFile.println("Result: " + result);
outputFile.flush();
outputFile.close();
file.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e1) {
e1.printStackTrace();
}
return result;
} else {
System.out.println("End of elements in the stream.");
String result = "End of elements in the input data";
return result;
}
}
}).cache();
long processedRecords = classificationResults.count();
ssc.stop();
System.out.println("sssssssssss"+processedRecords);
}
}
Here is the KryoRegistrator class
package org.apache.spark.examples;
import org.apache.spark.serializer.KryoRegistrator;
import com.esotericsoftware.kryo.Kryo;
public class MyRegistrator implements KryoRegistrator {
public void registerClasses(Kryo kryo) {
kryo.register(NotSerializableJavaClass.class);
}
}
Here is the class I am serializing :
package org.apache.spark.examples;
public class NotSerializableJavaClass {
public String testVariable;
public NotSerializableJavaClass(String testVariable) {
super();
this.testVariable = testVariable;
}
public String testMethod(String vartoAppend){
return this.testVariable + vartoAppend;
}
}
This is because spark.closure.serializer only supports the Java serializer. See http://spark.apache.org/docs/latest/configuration.html about spark.closure.serializer
sorry I am a newbie I have been looking for an example on how I can iterate hashmap and store the entities into MySQL database. the blow code downloads currency rate which I would like to store into my database. the output is
{CCY=USD, RATE=1.5875}
{CCY=EUR, RATE=1.1919}
{CCY=ALL, RATE=166.2959}
{CCY=AMD, RATE=645.4025}
how can I iterate the HashMap and store it into my database? an illustration would be nice or source similar to this scenario.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Rate {
/** list of string array containing IOSCurrencyCodes*/
final String[] CURRENCY = new String[] { "USD","EUR","ALL","AMD",};
#SuppressWarnings("rawtypes")
void checkRateAllAtEnd() throws Exception {
List<Callable<HashMap>> tasks = new ArrayList<Callable<HashMap>>();
for (final String ccy : CURRENCY) {
tasks.add(new Callable<HashMap>() {
public HashMap<String, Comparable> call() throws Exception {
return getRates(ccy);
}
});
}
ExecutorService executorPool = Executors.newCachedThreadPool();
final List<Future<HashMap>> listRates = executorPool.invokeAll(tasks, 3600, TimeUnit.SECONDS);
for (Future<HashMap> rate : listRates) {
HashMap ccyRate = rate.get();
System.out.println(ccyRate);
}
}
#SuppressWarnings("rawtypes")
public HashMap<String, Comparable> getRates(String ccy) throws Exception {
URL url = new URL("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=GBP"
+ ccy + "=X");
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream()));
String data = reader.readLine();
String[] dataItems = data.split(",");
Double rate = Double.valueOf(dataItems[1]);
HashMap<String, Comparable> ccyRate = new HashMap<String, Comparable>();
ccyRate.put("CCY", ccy);
ccyRate.put("RATE", rate);
return ccyRate;
}
public static void main(String[] args) {
Rate ccyRate = new Rate();
try {
//ccyConverter.checkRateSequential();
ccyRate.checkRateAllAtEnd();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Map provides entrySet method which is very useful to iterate over a map.
Map#entrySet returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress.
ref - link
Code -
HashMap<String, Comparable> ccyRate = new HashMap<String, Comparable>();
for(Map.Entry<String, Comparable> entry: ccyRate.entrySet){
System.out.println(entry.getKey()+" - "+entry.getValue());
}
I'm a rookie with Esper and I would like to get some help. I've already managed to use Esper with CSV files, but now I need to use Java objects as events sent through a socket and I can't find simple examples on the Internet to use as a guide.
Has anybody some simple examples to base on them?
Anyway, I let here the code I am trying to make work. Nothing happens when I run it, it seems the socket connection does not work.
The server class (it also contains the event class). It is suposed to send the events:
import java.io.* ;
import java.net.* ;
class Server {
static final int PORT=5002;
public Server( ) {
try {
ServerSocket skServer = new ServerSocket( PORT );
System.out.println("Listening at " + PORT );
Socket skClient = skServer.accept();
System.out.println("Serving to Esper");
OutputStream aux = skClient.getOutputStream();
ObjectOutputStream flux = new ObjectOutputStream( aux );
int i = 0;
while (i<10) {
flux.writeObject( new MeteoEvent(i,"A") );
i++;
}
flux.flush();
skClient.close();
System.out.println("End of transmission");
} catch( Exception e ) {
System.out.println( e.getMessage() );
}
}
public static void main( String[] arg ) {
new Server();
}
class MeteoEvent{
private int sensorId;
private String GeoArea;
public MeteoEvent() {
}
public MeteoEvent(int sensorid, String geoarea) {
this.sensorId = sensorid;
this.GeoArea = geoarea;
}
public int getSensorId() {
return sensorId;
}
public void setSensorId(int sensorId) {
this.sensorId = sensorId;
}
public String getGeoArea() {
return GeoArea;
}
public void setGeoArea(String geoArea) {
GeoArea = geoArea;
}
}
}
And the Esper-based class.
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.espertech.esper.client.Configuration;
import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPRuntime;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPServiceProviderManager;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.UpdateListener;
import com.espertech.esper.event.map.MapEventBean;
import com.espertech.esperio.socket.EsperIOSocketAdapter;
import com.espertech.esperio.socket.config.ConfigurationSocketAdapter;
import com.espertech.esperio.socket.config.DataType;
import com.espertech.esperio.socket.config.SocketConfig;
public class Demo {
public static class CEPListener implements UpdateListener {
private String tag;
public CEPListener (String tag)
{
this.tag = tag;
}
public static void main(String[] args) throws IOException, InterruptedException {
Configuration configuration = new Configuration();
Map<String, Object> eventProperties = new HashMap<String, Object>();
eventProperties.put("sensorId", int.class);
eventProperties.put("GeoArea", String.class);
configuration.addEventType("MeteoEvent", eventProperties);
ConfigurationSocketAdapter socketAdapterConfig = new ConfigurationSocketAdapter();
SocketConfig socketConfig = new SocketConfig();
socketConfig.setDataType(DataType.OBJECT);
socketConfig.setPort(5002);
socketAdapterConfig.getSockets().put("MeteoSocket", socketConfig);
EPServiceProvider cepService = EPServiceProviderManager.getProvider("MeteoSocket",configuration);
EPRuntime cepServiceRT = cepService.getEPRuntime();
EPAdministrator cepAdmin = cepService.getEPAdministrator();
EsperIOSocketAdapter socketAdapter = new EsperIOSocketAdapter (socketAdapterConfig, "MeteoSocket");
socketAdapter.start();
EPStatement stmt = cepAdmin.createEPL("insert into JoinStream select * from MeteoEvent");
EPStatement outputStatementX = cepAdmin.createEPL("select * from JoinStream");
outputStatementX.addListener(new CEPListener("JS"));
cepService.initialize();
Object lock = new Object();
synchronized (lock)
{
lock.wait();
}
}
Thank you very much in advance if anyone takes some time trying to help me.
Problem solved! The Esper Dev list was very useful. I learned how to use Esper + sockets through the test classes located here
Best regards!