Added socket.io PoC

master
J.Fernando Sánchez 12 years ago
parent 8a517c87a0
commit e725d7a733

1
bin/.gitignore vendored

@ -0,0 +1 @@
classes

@ -5,18 +5,18 @@
This file was generated by Jason 1.3.6a
http://jason.sf.net
March 20, 2012 - 16:30:55
March 22, 2012 - 19:46:25
-->
<project name ="web40sojason"
basedir=".."
default="run">
<property name="mas2j.project.file" value="Web40SOJason.mas2j"/>
<property name="mas2j.project.file" value="testSocket.mas2j"/>
<property name="debug" value=""/> <!-- use "-debug" to run in debug mode -->
<property name="build.dir" value="${basedir}/bin/classes" />
<property name="jasonJar" value="/home/miguel/trabajo/Jason-1.3.6a/lib/jason.jar"/>
<property name="jasonJar" value="/media/Data/Programs/eclipse/./lib/jason.jar"/>
<path id="project.classpath">
<pathelement location="${basedir}"/>
@ -73,10 +73,10 @@
<copy todir="${basedir}/${ant.project.name}-jws" failonerror="no">
<fileset dir="${basedir}/lib" includes="**/*.jar" />
<fileset dir="${basedir}" includes="${ant.project.name}.jar" />
<fileset dir="/home/miguel/trabajo/Jason-1.3.6a/src/images" includes="Jason-GMoreau-Icon.jpg" />
<fileset dir="/media/Data/Programs/eclipse/./src/images" includes="Jason-GMoreau-Icon.jpg" />
</copy>
<signjar jar="${basedir}/${ant.project.name}-jws/${ant.project.name}.jar" alias="jason"
storepass="rbjhja" keypass="rbjhja" keystore="/home/miguel/trabajo/Jason-1.3.6a/src/jasonKeystore" />
storepass="rbjhja" keypass="rbjhja" keystore="/media/Data/Programs/eclipse/./src/jasonKeystore" />
<echo message="**" />
<echo message="** Java Web Start application created in directory ${ant.project.name}-jws" />
<echo message="** Update the codebase (in the second line of the .jnlp file)" />

@ -0,0 +1,8 @@
// Agent userAgent in project Web40
/* Initial beliefs and rules */
/* Initial goals */
/* Plans */

@ -0,0 +1,40 @@
// Agent nluAgent in project Web40SOJason
/* Initial beliefs and rules */
/* Initial goals */
/* Plans */
@in_msg
+user_msg(Msg, Query) : true
<- sendNLU(Query, Msg);
-user_msg(Msg, Query). // clear the memory
/* Tell the user agent what the NLU system understood */
+price(Terms, Price)[query(Query), domain(travel)] : true
<- .send(userAgent, tell, price(Terms, Price)[query(Query)], domain(travel));
.print("Percibido: price ",Terms, " ", Price ).
+date(Terms, Day, Month, Year)[query(Query), domain(travel)] : true
<- .send(userAgent, tell, date(Terms, Day, Month, Year)[query(Query), domain(travel)]);
.print("Percibido: date ",Terms, " ", Day, " ", Month, " ", Year).
+time(Terms, Hours, Minutes)[query(Query), domain(travel)] : true
<- .send(userAgent, tell, time(Terms, Hours, Minutes)[query(Query), domain(travel)]);
.print("Percibido: time ",Terms, " ", Hours, " ", Minutes).
+location(Terms, Place)[query(Query), domain(travel)] : true
<- .send(userAgent, tell, location(Terms, Place)[query(Query), domain(travel)]);
.print("Percibido: location ",Terms, " ", Place).
+type(Terms)[query(Query), domain(travel)] : true
<- .send(userAgent, tell, type(Terms)[query(Query), domain(travel)]);
.print("Percibido: type ",Terms).
@sendFindTravel
+done[query(Query), domain(Domain)] : true
<- .wait(1000); // wait until all other information is sent
.print("Percepcion completada");
.send(userAgent, achieve, find(Domain, Query)).

@ -0,0 +1,12 @@
// Agent testAgent in project Web40 - For socket.io
!start.
/* Wait for service introduction (temporal plan, to erase) */
+!start : true
<- +have(started);
.print("Hola");
.wait(1000);
sendSocket("test","hola").
+success(yes): true
<- .print("Succes!!!!!").

@ -0,0 +1,60 @@
// Agent travelAgent in project Web40
/* Initial beliefs and rules */
canFindTravel(Query)
:- location(from,_)[query(Query)] &
location(to,_)[query(Query)] &
date(departure,_,_,_)[query(Query)].
/* Initial goals */
contact(userAgent).
my_service(travel).
my_service(train).
/************** Plans *****************/
/* Introduce myself to the user agent */
@introduce_myself
+my_service(Domain)
: contact(Agent) & .my_name(Me)
<- .send(Agent, tell, service(Me, Domain)).
@introduction_rety
+my_service(Domain) : not contact(Agent)
<- -+my_service(Domain).
/* Find travel plans */
@findTravel1
+!find(travel, Query) : not canFindTravel(Query) & not delay(Query)
<- .print("Not enought data. Lets wait some time");
.wait(3000);
+delay(Query);
!find(travel, Query).
@findTravel2
+!find(travel, Query) : not canFindTravel(Query) & delay(Query)
<- -delay(Query);
.print("Not enought data. Lets ask!").
@findTravel3
+!find(travel, Query) : canFindTravel(Query)
<- ?location(to, To);
?location(from, From);
?date(departure, Day, Month, Year);
findTravel(From, To, Day, Month, Year);
.print("ok").
@findTravelFailureRety
-!find(travel, Query) : not error(Msg, Query)<- !findTravel(Query).
@findTravelFailureError
-!find(travel, Query) : error(Msg, Query)
<- .print("Problema al encontrar viajes:", Msg);
!findTravel(Query).
/* log results */
@log_the_journey
+journey(From, To, Departure, Arrival, Fares) : true
<- .print("Travel found: From ", From,"<", Departure, "> to ", To, "<", Arrival, "> for ", Fares).

@ -0,0 +1,56 @@
// Agent userAgent in project Web40
/* Initial beliefs and rules */
new_query(Query) :- .random(R) & Query = (1000*R)+1.
!start.
/* Initial goals */
/******* Plans ***************************/
/* Wait for service introduction (temporal plan, to erase) */
+!start : true
<- .wait(1000);
+user_msg("I want to travel from Madrid to Cuenca in the morning that costs no more than 200€ and dinner in a romantic restaurant").
/* Ask the nlu agent */
+user_msg(Msg) : new_query(Query)
<- .send(nluAgent, tell, user_msg(Msg, Query) ).
/* Log the received data */
+price(Terms, Price)[query(Query), domain(Domain)] : true
<- .print("Percibido: price ",Terms, " ", Price );
+data(price(Terms), Query, Domain).
+date(Terms, Day, Month, Year)[query(Query), domain(Domain)] : true
<- .print("Percibido: date ",Terms, " ", Day, " ", Month, " ", Year);
+data(date(Terms, Day, Month, Year), Query, Domain).
+time(Terms, Hours, Minutes)[query(Query), domain(Domain)] : true
<- .print("Percibido: time ",Terms, " ", Hours, " ", Minutes);
+data(time(Terms, Hours, Minutes), Query, Domain).
+location(Terms, Place)[query(Query), domain(Domain)] : true
<- .print("Percibido: location ",Terms, " ", Place);
+data(location(Terms, Place), Query, Domain).
+type(Terms)[query(Query), domain(Domain)] : true
<- .print("Percibido: type ",Terms).
/* find travel */
/*@find_travel
+!find(travel, Query) : true
<- .println("lets find travel ", Query);
.findall(Name, service(Name, travel), List);
.send(List, achieve, find(travel, Query)).
*/
@do_search
+!find(Domain, Query) : true
<- .print("Perform find ", Domain, " ", Query);
.findall(Name, service(Name, Domain), AgList);
.findall(Atom[query(Query)], data(Atom, Query, Domain), DataList);
.send(AgList, tell, DataList);
.send(AgList, achieve, find(Domain, Query)).

@ -0,0 +1 @@
socket.io-java-client : https://github.com/Gottox/socket.io-java-client

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,18 @@
Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
-Redistribution of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
-Redistribution in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of Sun Microsystems, Inc. or the names of contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
This software is provided "AS IS," without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
You acknowledge that this software is not designed, licensed or intended for use in the design, construction, operation or maintenance of any nuclear facility.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

@ -0,0 +1,12 @@
// Agent testAgent in project Web40 - For socket.io
!start.
/* Wait for service introduction (temporal plan, to erase) */
+!start : true
<- +have(started);
.print("Hola");
.wait(1000);
sendSocket("test","hola").
+success(yes): true
<- .print("Succes!!!!!").

@ -57,7 +57,11 @@ public class SOEnvironment extends Environment {
result = this.model.sendNlu(agName, terms);
}
else if (functor.equals("findTravel")) {
result = this.model.findTravel(agName, terms);
this.model.findTravel(agName, terms);
return true;
}
else if (functor.equals("sendSocket")) {
result = this.model.sendSocket(agName, terms);
return true;
}
else {

@ -9,6 +9,7 @@ import java.util.logging.Logger;
import es.upm.dit.gsi.jason.utils.CollectionUtils;
import es.upm.dit.gsi.sojason.services.nlu.NLUConnector;
import es.upm.dit.gsi.sojason.services.socketio.SocketIOConnector;
import es.upm.dit.gsi.sojason.services.travel.RenfeScrapper;
/**
@ -26,12 +27,15 @@ public class Web40Model extends SOModel{
/** */
public final static String NLU_SERVICE_URL = "http://46.4.52.82:3333/nlu";
public final static String SOCKET_SERVICE_URL = "http://localhost:3000";
/** */
private NLUConnector nluConnector;
/** */
private RenfeScrapper renfeScrapper;
/** */
private Logger logger = Logger.getLogger("Web40SOJason." + Web40Model.class.getName());
private SocketIOConnector socketConnector;
/** Constructor
* @throws IOException */
@ -39,6 +43,7 @@ public class Web40Model extends SOModel{
super();
this.nluConnector = new NLUConnector(NLU_SERVICE_URL);
this.renfeScrapper = new RenfeScrapper();
this.socketConnector = new SocketIOConnector(SOCKET_SERVICE_URL);
}
/**
@ -95,4 +100,33 @@ public class Web40Model extends SOModel{
}
/**
*
* @param agName
* @param terms
* @return
*/
public boolean sendSocket (String agName, Collection<Term> params) {
logger.info("Entering sendSocket...");
try{
String[] strParams = CollectionUtils.toStringArray(params);
boolean serviceData = socketConnector.call(this,agName,strParams);
if(serviceData == false){
logger.info("Could not complete action socketIO: false!");
return false;
}
// put data into mailbox
// this.setDataInbox(agName, serviceData);
}
catch (Exception e){
logger.info("Could not complete action SocketIO (error):" + e.getCause() + "_"+e.getCause()+"_"+e.getMessage());
return false;
}
logger.info("SocketConnector call completed successfully");
return true;
}
}

@ -13,28 +13,28 @@ import es.upm.dit.gsi.jason.utils.NotationUtils;
/**
* @author miguel
*
*
*/
public class Journey implements Perceptable{
public class Journey implements Perceptable {
/** The departure time of the journey */
private String departureTime;
/** The arrival time of the journey */
private String arrivalTime;
/**
* The duration of the journey. This is not simply the difference of the
/**
* The duration of the journey. This is not simply the difference of the
* departure and arrival time because of timezone considerations.
*/
private String duration;
/** The origin */
private String origin;
/** The destination */
private String destination;
/** The fee map that contains the different available fee */
private Map<String, String> fares;
@ -46,7 +46,8 @@ public class Journey implements Perceptable{
}
/**
* @param departureTime the departureTime to set
* @param departureTime
* the departureTime to set
*/
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
@ -60,7 +61,8 @@ public class Journey implements Perceptable{
}
/**
* @param arrivalTime the arrivalTime to set
* @param arrivalTime
* the arrivalTime to set
*/
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
@ -74,7 +76,8 @@ public class Journey implements Perceptable{
}
/**
* @param duration the duration to set
* @param duration
* the duration to set
*/
public void setDuration(String duration) {
this.duration = duration;
@ -88,7 +91,8 @@ public class Journey implements Perceptable{
}
/**
* @param oringin the oringin to set
* @param oringin
* the oringin to set
*/
public void setOrigin(String origin) {
this.origin = origin;
@ -102,7 +106,8 @@ public class Journey implements Perceptable{
}
/**
* @param destination the destination to set
* @param destination
* the destination to set
*/
public void setDestination(String destination) {
this.destination = destination;
@ -116,15 +121,16 @@ public class Journey implements Perceptable{
}
/**
* @param fares the fares to set
* @param fares
* the fares to set
*/
public void setFares(Map<String, String> fares) {
this.fares = fares;
}
/** Textual representation of the journey. Use for debuging purposes inly.*/
/** Textual representation of the journey. Use for debuging purposes inly. */
public String toString() {
String toString = "From: ";
toString = toString.concat(origin);
toString = toString.concat(" (");
@ -136,69 +142,72 @@ public class Journey implements Perceptable{
toString = toString.concat(") in ");
toString = toString.concat(duration);
toString = toString.concat(" for ");
if(fares != null)
if (fares != null)
toString = toString.concat(fares.toString());
else
toString += null;
return toString;
}
/**
* journey(madrid, ciudad_real, 10.15, 11.5, [fare(turista, 22.5), fare(preferente, 35)]
* journey(madrid, ciudad_real, time(10,15), time(11,5), [fare(turista, 22.5), fare(preferente, 35)]
* journey(madrid, ciudad_real, 10.15, 11.5, [fare(turista, 22.5),
* fare(preferente, 35)] journey(madrid, ciudad_real, time(10,15),
* time(11,5), [fare(turista, 22.5), fare(preferente, 35)]
*
* @return
*/
public List<Literal> toPercepts() {
// if (this.fares.size() == 0){ return null; }
//
// String percept = "journey(";
// percept = percept.concat(this.origin);
// percept = percept.concat(", ");
// percept = percept.concat(this.destination);
// percept = percept.concat(", ");
// percept = percept.concat(this.departureTime);
// percept = percept.concat(", ");
// percept = percept.concat(this.arrivalTime);
//
// percept = percept.concat(", [");
// for(String fareName : fares.keySet()) {
// percept = percept.concat("fare(");
// percept = percept.concat(fareName);
// percept = percept.concat(", ");
// percept = percept.concat(fares.get(fareName));
// percept = percept.concat("), ");
// }
// percept = percept.substring(0, percept.lastIndexOf(","));
// percept = percept.concat("])");
//
// LinkedList<Literal> ret = new LinkedList<Literal>();
// ret.add(Literal.parseLiteral(percept));
//
// return ret;
if (this.fares.size() == 0){ return null; }
// if (this.fares.size() == 0){ return null; }
//
// String percept = "journey(";
// percept = percept.concat(this.origin);
// percept = percept.concat(", ");
// percept = percept.concat(this.destination);
// percept = percept.concat(", ");
// percept = percept.concat(this.departureTime);
// percept = percept.concat(", ");
// percept = percept.concat(this.arrivalTime);
//
// percept = percept.concat(", [");
// for(String fareName : fares.keySet()) {
// percept = percept.concat("fare(");
// percept = percept.concat(fareName);
// percept = percept.concat(", ");
// percept = percept.concat(fares.get(fareName));
// percept = percept.concat("), ");
// }
// percept = percept.substring(0, percept.lastIndexOf(","));
// percept = percept.concat("])");
//
// LinkedList<Literal> ret = new LinkedList<Literal>();
// ret.add(Literal.parseLiteral(percept));
//
// return ret;
if (this.fares.size() == 0) {
return null;
}
String percept = "journey(";
percept = percept.concat(NotationUtils.compact(this.origin));
percept = percept.concat(", ");
percept = percept.concat(NotationUtils.compact(this.destination));
percept = percept.concat(", time(");
String digits[] = this.departureTime.split("[\\x2E\\x3A]"); // [.:]
percept = percept.concat(digits[0]);
percept = percept.concat(", ");
percept = percept.concat(digits[1]);
percept = percept.concat("), time(");
digits = this.arrivalTime.split("[\\x2E\\x3A]"); // [.:]
percept = percept.concat(digits[0]);
percept = percept.concat(", ");
percept = percept.concat(digits[1]);
percept = percept.concat("), [");
for(String fareName : fares.keySet()) {
for (String fareName : fares.keySet()) {
percept = percept.concat("fare(");
percept = percept.concat(NotationUtils.compact(fareName));
percept = percept.concat(", ");
@ -207,10 +216,10 @@ public class Journey implements Perceptable{
}
percept = percept.substring(0, percept.lastIndexOf(","));
percept = percept.concat("])");
LinkedList<Literal> ret = new LinkedList<Literal>();
ret.add(Literal.parseLiteral(percept));
return ret;
}

@ -0,0 +1,57 @@
/**
*
*/
package es.upm.dit.gsi.sojason.services;
import es.upm.dit.gsi.sojason.SOModel;
/**
* This interface defines a standard way to connect to a web service in
* the definition of an external action in Jason.
*
* Project: Web40SOJason
* Package: es.upm.dit.gsi.sojason.services
* Class: WebServiceConnector
*
* @author Miguel Coronado (miguelcb@dit.upm.es)
* @version Feb 27, 2012
*
*/
public interface AsyncWebServiceConnector {
/**
* This calls the service including in the request the parameters given.
* The URL of the service, the method to use and any other particularity
* of the transaction to connect to the service must be determined in the
* implementation of the method.
*
* @param params The list of parameters to include in the service
* request. Due to this is not a <code>Dictionary</code>
* the order of the parameters it is important and will be
* determined by the implementation of the extendee
* classes.
* @return Whether the call was successful or not.
*/
public boolean call(SOModel model, String agname, String... params);
/**
* This validates the set of parameters provided. Typically, this method
* should use some regex exprsesions to check whether a parameter is valid
* or not, due to the nature of the parameter cannot be checked because of
* the type of the parameters has been unified to String.
*
* @param params The list of parameters to validate
*/
public boolean validateParams(String... params);
/**
* This generates a set of error <code>Literal</code>s that describes the
* errors committed when trying to call the given service with the set of
* parameters given.
*
* @param params The list of parameters
*/
// public Set<Literal> checkForErrors(String... params);
}

@ -0,0 +1,131 @@
package es.upm.dit.gsi.sojason.services.socketio;
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import jason.asSyntax.Literal;
import java.net.MalformedURLException;
import java.util.logging.Logger;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import es.upm.dit.gsi.sojason.SOModel;
import es.upm.dit.gsi.sojason.services.AsyncWebServiceConnector;
/**
* Project: Web40SOJason
* Package: es.upm.dit.gsi.sojason.services.nlu
* Class: NLUConnector
*
* @author Miguel Coronado (miguelcb@dit.upm.es)
* @version Feb 27, 2012
*
*/
public class SocketIOConnector implements AsyncWebServiceConnector{
/** The url of the service */
private String serviceUrl;
/** */
private Logger logger = Logger.getLogger("Web40SOJason." + SocketIOConnector.class.getName());
private static SocketIO socket;
static IOCallback callback = new IOCallback() {
public void onMessage(JSONObject json, IOAcknowledge ack) {
System.out.println("Message:" + json.toString());
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Message:" + data);
}
@Override
public void onError(SocketIOException socketIOException) {
System.out.println("Error");
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
}
@Override
public void onConnect() {
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
}
@Override
public void onMessage(org.json.JSONObject arg0, IOAcknowledge arg1) {
// TODO Auto-generated method stub
}
};
//TODO Remove try-catch
/** Constructor */
public SocketIOConnector(String serviceUrl) {
this.serviceUrl = serviceUrl;
try {
socket = new SocketIO();
socket.connect(serviceUrl, callback);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
*
*/
public boolean call(final SOModel model, final String agName, String... params) {
logger.info("Calling SocketIOConnector with"+params[0]);
try {
socket.emit("test", new IOAcknowledge() {
@Override
public void ack(Object... args) {
logger.info("Package ack'ed");
Literal lit = Literal.parseLiteral("success(yes)");
model.setDataInbox(agName, lit);
logger.info("DataInbox set");
}
}, new JSONObject().put("Hello", "Planeta"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* This validates the parameters received. The
* {@link SocketIOConnector#call(String...)} method expects to receive two
* parameters of the nature and characteristics described below:
*
* <ul>
* <li>The first parameter is que query id. It is an alphanumeric string
* which normally will contain numbers, but other non-digit characters
* are permitted. <b>No alphanumeric values are not allowed</b></li>
* <li></li>
* </ul>
*
*/
public boolean validateParams(String... params) {
if (params.length != 2){
return false;
}
// TODO: check other things
return true;
}
}

@ -0,0 +1,16 @@
/*
Jason Project
-- create on March 19, 2012
*/
MAS web40sojason {
infrastructure: Centralised
environment: es.upm.dit.gsi.sojason.SOEnvironment
agents:
testAgent;
aslSourcePath: "src/asl";
}
Loading…
Cancel
Save