Commit bc20e241 authored by Renato Figueiro Maia's avatar Renato Figueiro Maia

[OPENBUS-1736] [LUA] Implementar demos para o SDK 2.0

git-svn-id: https://subversion.tecgraf.puc-rio.br/engdist/openbus/sdk/lua/branches/openbus_v2_proto@132042 ae0415b3-e90b-0410-900d-d0be9363c56b
parent 0fb8787e
local utils = require "utils"
local openbus = require "openbus"
-- process command-line arguments
local bushost, busport, entity, password = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
local params = {
bushost = bushost,
busport = busport,
entity = entity,
}
local repID = "IDL:Messenger:1.0"
-- variable to hold resources to be freed before termination
local conn
-- function that uses the bus to find the required service
local function findService()
-- connect to the bus
local connections = openbus.initORB().OpenBusConnectionManager
conn = connections:createConnection(bushost, busport)
connections:setDefaultConnection(conn)
-- login to the bus
conn:loginByPassword(entity, password or entity)
-- find the offered service
return conn.offers:findServices{
{name="openbus.component.interface",value=repID},
{name="offer.domain",value="Demo Chain Validation"},
}
end
-- function that uses the required service through the bus
local function callService(offer)
service = offer.service_ref
if not service:_non_existent() then
local facet = service:getFacet(repID)
if facet ~= nil then
facet:__narrow():showMessage("Hello!")
return true
end
end
end
-- perform operations in protected mode and handle eventual errors
local ok, result = pcall(findService)
if not ok then
utils.showerror(result, params, utils.msg.Connect, utils.msg.LoginByPassword)
else
ok = nil
for _, offer in ipairs(result) do
ok, result = pcall(callService, offer)
if not ok then
if result._repid == "IDL:Unauthorized:1.0" then
io.stderr:write("serviço com papel ",utils.getprop(offer, "offer.role"),
" não autorizou a chamada\n")
elseif result._repid == "IDL:Unavailable:1.0" then
io.stderr:write("serviço com papel ",utils.getprop(offer, "offer.role"),
" está indisponível\n")
else
utils.showerror(result, params, utils.msg.Service)
end
end
end
if ok == nil then
io.stderr:write("não foi possível encontrar o serviço esperado\n")
end
end
-- free any resoures allocated
if conn ~= nil then conn:logout() end
exception Unavailable {};
exception Unauthorized {};
interface Messenger {
void showMessage(in string message) raises (Unavailable, Unauthorized);
};
local utils = require "utils"
local server = require "openbus.util.server"
local openbus = require "openbus"
local ComponentContext = require "scs.core.ComponentContext"
-- process command-line arguments
local bushost, busport, entity, privatekeypath = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
privatekeypath = assert(privatekeypath,
"o 4o. argumento é o caminho da chave privada de autenticação da entidade")
local privatekey = assert(server.readfrom(privatekeypath))
local params = {
bushost = bushost,
busport = busport,
entity = entity,
privatekeypath = privatekeypath,
}
-- setup and start the ORB
local orb = openbus.initORB()
openbus.newthread(orb.run, orb)
-- load interface definitions
orb:loadidlfile("callchain/messenger.idl")
local iface = orb.types:lookup("Messenger")
params.interface = iface.name
-- create service implementation
local offers
local function callService(message)
if offers ~= nil then
for _, offer in ipairs(offers) do
service = offer.service_ref
if not service:_non_existent() then
local facet = service:getFacet(iface.repID)
if facet ~= nil then
facet:__narrow():showMessage(message)
return true
end
end
end
end
end
local function chain2str(chain)
local entities = {}
for _, login in ipairs(chain.originators) do
entities[#entities+1] = login.entity
end
entities[#entities+1] = chain.caller.entity
return table.concat(entities, "->")
end
local conn
local messenger = {}
function messenger:showMessage(message)
local chain = conn:getCallerChain()
print("repassando mensagem de "..chain2str(chain))
conn:joinChain(chain)
local ok, result = pcall(callService, message)
if not ok then
utils.showerror(result, params, utils.msg.Service)
elseif not result then
print(" nenhum serviço encontrado para repassar mensagem")
error{_repid="IDL:Unavailable:1.0"}
end
end
-- create service SCS component
local component = ComponentContext(orb, {
name = iface.name,
major_version = 1,
minor_version = 0,
patch_version = 0,
platform_spec = "Lua",
})
component:addFacet(iface.name, iface.repID, messenger)
-- call in protected mode
local ok, result = pcall(function ()
-- connect to the bus
local connections = orb.OpenBusConnectionManager
conn = connections:createConnection(bushost, busport)
connections:setDefaultConnection(conn)
-- login to the bus
conn:loginByCertificate(entity, privatekey)
-- register service at the bus
conn.offers:registerService(component.IComponent, {
{name="offer.role",value="proxy messenger"},
{name="offer.domain",value="Demo Chain Validation"},
})
-- find the offered service
offers = conn.offers:findServices{
{name="openbus.component.interface",value=iface.repID},
{name="offer.role",value="actual messenger"},
{name="offer.domain",value="Demo Chain Validation"},
}
end)
-- show eventual errors
if not ok then
utils.showerror(result, params,
utils.msg.Connect,
utils.msg.LoginByCertificate,
utils.msg.Register)
-- free any resoures allocated
if conn ~= nil then
conn:logout()
end
orb:shutdown()
end
local utils = require "utils"
local server = require "openbus.util.server"
local openbus = require "openbus"
local ComponentContext = require "scs.core.ComponentContext"
-- process command-line arguments
local bushost, busport, entity, privatekeypath = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
privatekeypath = assert(privatekeypath,
"o 4o. argumento é o caminho da chave privada de autenticação da entidade")
local privatekey = assert(server.readfrom(privatekeypath))
local params = {
bushost = bushost,
busport = busport,
entity = entity,
privatekeypath = privatekeypath,
}
-- setup and start the ORB
local orb = openbus.initORB()
openbus.newthread(orb.run, orb)
-- load interface definitions
orb:loadidlfile("callchain/messenger.idl")
local iface = orb.types:lookup("Messenger")
params.interface = iface.name
-- create service implementation
local function chain2str(chain)
local entities = {}
for _, login in ipairs(chain.originators) do
entities[#entities+1] = login.entity
end
entities[#entities+1] = chain.caller.entity
return table.concat(entities, "->")
end
local conn
local messenger = {}
function messenger:showMessage(message)
local chain = conn:getCallerChain()
if chain.caller.entity ~= entity then
print("recusando mensagem de "..chain2str(chain))
error{_repid="IDL:Unauthorized:1.0"}
end
print("aceitando mensagem de "..chain2str(chain)..":", message)
end
-- create service SCS component
local component = ComponentContext(orb, {
name = iface.name,
major_version = 1,
minor_version = 0,
patch_version = 0,
platform_spec = "Lua",
})
component:addFacet(iface.name, iface.repID, messenger)
-- call in protected mode
local ok, result = pcall(function ()
-- connect to the bus
local connections = orb.OpenBusConnectionManager
conn = connections:createConnection(bushost, busport)
connections:setDefaultConnection(conn)
-- login to the bus
conn:loginByCertificate(entity, privatekey)
-- register service at the bus
conn.offers:registerService(component.IComponent, {
{name="offer.role",value="actual messenger"},
{name="offer.domain",value="Demo Chain Validation"},
})
end)
-- show eventual errors
if not ok then
utils.showerror(result, params,
utils.msg.Connect,
utils.msg.LoginByCertificate,
utils.msg.Register)
-- free any resoures allocated
if conn ~= nil then
conn:logout()
end
orb:shutdown()
end
local utils = require "utils"
local except = require "openbus.util.except"
local openbus = require "openbus"
-- process command-line arguments
local bushost, busport, entity, password, interval, timeout = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
interval = assert(tonumber(interval or 1), "o 5o. argumento é um tempo entre "..
"tentativas de acesso ao barramento em virtude de falhas")
retries = assert(tonumber(timeout or 10), "o 6o. argumento é o número máximo "..
"de tentativas de acesso ao barramento em virtude de falhas")
local params = {
bushost = bushost,
busport = busport,
entity = entity,
}
-- independent clock thread
function retry()
if retries > 0 then
retries = retries-1
openbus.sleep(interval)
return true
end
end
-- setup the ORB
local orb = openbus.initORB()
-- connect to the bus
local conn
local connections = orb.OpenBusConnectionManager
repeat
local ok, result = pcall(connections.createConnection, connections, bushost,
busport)
if ok then
conn = result
else
utils.showerror(result, params, utils.msg.Connect)
if not retry() then
return
end
end
until ok
connections:setDefaultConnection(conn)
-- define callback for auto-relogin
function conn:onInvalidLogin()
repeat
local ok, result = pcall(conn.loginByPassword, conn, entity, password
or entity)
if not ok then
if result._repid == except.repid.AlreadyLoggedIn then
ok = true -- ignore this exception
else
utils.showerror(result, params, utils.msg.LoginByPassword)
end
end
until ok or not retry()
end
-- login to the bus
conn:onInvalidLogin()
-- search for offer
local props = {{name="offer.domain",value="Demo Independent Clock"}}
local function getfacet(offer)
return orb:narrow(offer.service_ref:getFacetByName("Clock"))
end
local offers = conn.offers
repeat
local ok, result = pcall(offers.findServices, offers, props)
if ok then
for _, offer in ipairs(result) do
ok, result = pcall(getfacet, offer)
if not ok then
utils.showerror(result, params, utils.msg.Service)
elseif result == nil then
io.stderr:write("serviço encontrado não oferece a faceta esperada.\n")
else
ok, result = pcall(result.getTime, result)
if not ok then
utils.showerror(result, params, utils.msg.Service)
end
conn:logout()
return print(os.date(nil, result))
end
end
io.stderr:write("o serviço esperado não foi encontrado\n")
else
utils.showerror(result, params, utils.msg.Bus)
end
if not retry() then
conn:logout()
return
end
until false
local utils = require "utils"
local server = require "openbus.util.server"
local openbus = require "openbus"
local ComponentContext = require "scs.core.ComponentContext"
-- process command-line arguments
local bushost, busport, entity, privatekeypath, interval = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
privatekeypath = assert(privatekeypath,
"o 4o. argumento é o caminho da chave privada de autenticação da entidade")
local privatekey = assert(server.readfrom(privatekeypath))
interval = assert(tonumber(interval or 1), "o 5o. argumento é um tempo entre "..
"tentativas de acesso ao barramento em virtude de falhas")
local params = {
bushost = bushost,
busport = busport,
entity = entity,
privatekeypath = privatekeypath,
}
-- create service implementation
local clock = {}
function clock:getTime()
return os.time() - 24*60*60 -- send the time of the same moment yesterday
end
-- setup and start the ORB
local orb = openbus.initORB()
openbus.newthread(orb.run, orb)
-- create service SCS component
local iface = orb:loadidl("interface Clock { double getTime(); };")
params.interface = iface.name
local component = ComponentContext(orb, {
name = iface.name,
major_version = 1,
minor_version = 0,
patch_version = 0,
platform_spec = "Lua",
})
component:addFacet(iface.name, iface.repID, clock)
local props = {{name="offer.domain",value="Demo Independent Clock"}}
-- connect to the bus
local conn
local connections = orb.OpenBusConnectionManager
repeat
local ok, result = pcall(connections.createConnection, connections, bushost,
busport)
if ok then
conn = result
else
utils.showerror(result, params, utils.msg.Connect)
openbus.sleep(interval)
end
until ok
connections:setDefaultConnection(conn)
-- create thread to register offer after (re)login
local offer
local function doregister(self)
self.active = coroutine.running()
local offers = conn.offers
repeat
local ok, result = pcall(offers.registerService, offers,
component.IComponent, props)
if ok then
offer = result
else
utils.showerror(result, params, utils.msg.Register)
openbus.sleep(interval)
end
until ok
self.active = nil
end
local registerer = {}
function registerer:enable()
if offer == nil and self.active == nil then
openbus.newthread(doregister, self)
end
end
-- define callback for auto-relogin
function conn:onInvalidLogin()
offer = nil
repeat
local ok, result = pcall(conn.loginByCertificate, conn, entity, privatekey)
if not ok then
if result._repid == repid.AlreadyLoggedIn then
ok = true -- ignore this exception
else
utils.showerror(result, params, utils.msg.LoginByCertificate)
openbus.sleep(interval)
end
end
until ok
registerer:enable()
end
-- login to the bus
conn:onInvalidLogin()
local utils = require "utils"
local openbus = require "openbus"
-- process command-line arguments
local bushost, busport, entity, password, language = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
language = assert(language or "Portuguese",
"o 4o. argumento deve ser uma das opções: English, Spanish, Portuguese")
local params = {
bushost = bushost,
busport = busport,
entity = entity,
}
-- variable to hold resources to be freed before termination
local conn
-- function that uses the bus to find the required service
local function findService()
-- connect to the bus
local connections = openbus.initORB().OpenBusConnectionManager
conn = connections:createConnection(bushost, busport)
connections:setDefaultConnection(conn)
-- login to the bus
conn:loginByPassword(entity, password or entity)
-- find the offered service
return conn.offers:findServices{
{name="offer.domain",value="Demo Greetings"},
{name="greetings.language",value=language},
}
end
-- function that uses the required service through the bus
local facets = {"GoodMorning", "GoodAfternoon", "GoodNight"}
local function callService(offers)
for _, offer in ipairs(offers) do
service = offer.service_ref
if not service:_non_existent() then
for _, name in ipairs(facets) do
local facet = service:getFacetByName(name)
if facet == nil then
error("o serviço encontrado não oferece mais a faceta '"..name.."'")
end
facet:__narrow():sayGreetings()
end
return
end
end
error("não foi possível encontrar o serviço esperado")
end
-- perform operations in protected mode and handle eventual errors
local ok, result = pcall(findService)
if not ok then
utils.showerror(result, params, utils.msg.Connect, utils.msg.LoginByPassword)
else
ok, result = pcall(callService, result)
if not ok then
utils.showerror(result, params, utils.msg.Service)
end
end
-- free any resoures allocated
if conn ~= nil then conn:logout() end
local utils = require "utils"
local oo = require "openbus.util.oo"
local server = require "openbus.util.server"
local openbus = require "openbus"
local ComponentContext = require "scs.core.ComponentContext"
-- process command-line arguments
local bushost, busport, entity, privatekeypath = ...
bushost = assert(bushost, "o 1o. argumento é o host do barramento")
busport = assert(busport, "o 2o. argumento é a porta do barramento")
busport = assert(tonumber(busport), "o 2o. argumento é um número de porta")
entity = assert(entity, "o 3o. argumento é a entidade a ser autenticada")
privatekeypath = assert(privatekeypath,
"o 4o. argumento é o caminho da chave privada de autenticação da entidade")
local privatekey = assert(server.readfrom(privatekeypath))
local params = {
bushost = bushost,
busport = busport,
entity = entity,
privatekeypath = privatekeypath,
}
local messages = {
English = {
GoodMorning = "Good morning %s",
GoodAfternoon = "Good afternoon %s",
GoodNight = "Good night %s",
},
Spanish = {
GoodMorning = "Buenos días %s",
GoodAfternoon = "Buenas tardes %s",
GoodNight = "Buenas noches %s",
},
Portuguese = {
GoodMorning = "Bom dia %s",
GoodAfternoon = "Boa tarde %s",
GoodNight = "Boa noite %s",
},
}
-- create service implementation
local conn
local Greetings = oo.class{}
function Greetings:sayGreetings()
print(self.message:format(conn:getCallerChain().caller.entity))
end
-- setup and start the ORB
local orb = openbus.initORB()
openbus.newthread(orb.run, orb)
-- create service SCS component
local iface = orb:loadidl("interface Greetings { void sayGreetings(); };")
params.interface = iface.name